VirtualBox

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

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

Main: accident commit

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 432.4 KB
Line 
1/* $Id: MachineImpl.cpp 38999 2011-10-17 07:41:42Z 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 aLogFolder = mData->m_strConfigFileFull; // path/to/machinesfolder/vmname/vmname.vbox
6475 aLogFolder.stripFilename(); // path/to/machinesfolder/vmname
6476 aLogFolder.append(RTPATH_DELIMITER);
6477 aLogFolder.append("Logs"); // path/to/machinesfolder/vmname/Logs
6478}
6479
6480/**
6481 * Returns the full path to the machine's log file for an given index.
6482 */
6483Utf8Str Machine::queryLogFilename(ULONG idx)
6484{
6485 Utf8Str logFolder;
6486 getLogFolder(logFolder);
6487 Assert(logFolder.length());
6488 Utf8Str log;
6489 if (idx == 0)
6490 log = Utf8StrFmt("%s%cVBox.log",
6491 logFolder.c_str(), RTPATH_DELIMITER);
6492 else
6493 log = Utf8StrFmt("%s%cVBox.log.%d",
6494 logFolder.c_str(), RTPATH_DELIMITER, idx);
6495 return log;
6496}
6497
6498/**
6499 * Composes a unique saved state filename based on the current system time. The filename is
6500 * granular to the second so this will work so long as no more than one snapshot is taken on
6501 * a machine per second.
6502 *
6503 * Before version 4.1, we used this formula for saved state files:
6504 * Utf8StrFmt("%s%c{%RTuuid}.sav", strFullSnapshotFolder.c_str(), RTPATH_DELIMITER, mData->mUuid.raw())
6505 * which no longer works because saved state files can now be shared between the saved state of the
6506 * "saved" machine and an online snapshot, and the following would cause problems:
6507 * 1) save machine
6508 * 2) create online snapshot from that machine state --> reusing saved state file
6509 * 3) save machine again --> filename would be reused, breaking the online snapshot
6510 *
6511 * So instead we now use a timestamp.
6512 *
6513 * @param str
6514 */
6515void Machine::composeSavedStateFilename(Utf8Str &strStateFilePath)
6516{
6517 AutoCaller autoCaller(this);
6518 AssertComRCReturnVoid(autoCaller.rc());
6519
6520 {
6521 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6522 calculateFullPath(mUserData->s.strSnapshotFolder, strStateFilePath);
6523 }
6524
6525 RTTIMESPEC ts;
6526 RTTimeNow(&ts);
6527 RTTIME time;
6528 RTTimeExplode(&time, &ts);
6529
6530 strStateFilePath += RTPATH_DELIMITER;
6531 strStateFilePath += Utf8StrFmt("%04d-%02u-%02uT%02u-%02u-%02u-%09uZ.sav",
6532 time.i32Year, time.u8Month, time.u8MonthDay,
6533 time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond);
6534}
6535
6536/**
6537 * @note Locks this object for writing, calls the client process
6538 * (inside the lock).
6539 */
6540HRESULT Machine::launchVMProcess(IInternalSessionControl *aControl,
6541 const Utf8Str &strType,
6542 const Utf8Str &strEnvironment,
6543 ProgressProxy *aProgress)
6544{
6545 LogFlowThisFuncEnter();
6546
6547 AssertReturn(aControl, E_FAIL);
6548 AssertReturn(aProgress, E_FAIL);
6549
6550 AutoCaller autoCaller(this);
6551 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6552
6553 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6554
6555 if (!mData->mRegistered)
6556 return setError(E_UNEXPECTED,
6557 tr("The machine '%s' is not registered"),
6558 mUserData->s.strName.c_str());
6559
6560 LogFlowThisFunc(("mSession.mState=%s\n", Global::stringifySessionState(mData->mSession.mState)));
6561
6562 if ( mData->mSession.mState == SessionState_Locked
6563 || mData->mSession.mState == SessionState_Spawning
6564 || mData->mSession.mState == SessionState_Unlocking)
6565 return setError(VBOX_E_INVALID_OBJECT_STATE,
6566 tr("The machine '%s' is already locked by a session (or being locked or unlocked)"),
6567 mUserData->s.strName.c_str());
6568
6569 /* may not be busy */
6570 AssertReturn(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
6571
6572 /* get the path to the executable */
6573 char szPath[RTPATH_MAX];
6574 RTPathAppPrivateArch(szPath, sizeof(szPath) - 1);
6575 size_t sz = strlen(szPath);
6576 szPath[sz++] = RTPATH_DELIMITER;
6577 szPath[sz] = 0;
6578 char *cmd = szPath + sz;
6579 sz = RTPATH_MAX - sz;
6580
6581 int vrc = VINF_SUCCESS;
6582 RTPROCESS pid = NIL_RTPROCESS;
6583
6584 RTENV env = RTENV_DEFAULT;
6585
6586 if (!strEnvironment.isEmpty())
6587 {
6588 char *newEnvStr = NULL;
6589
6590 do
6591 {
6592 /* clone the current environment */
6593 int vrc2 = RTEnvClone(&env, RTENV_DEFAULT);
6594 AssertRCBreakStmt(vrc2, vrc = vrc2);
6595
6596 newEnvStr = RTStrDup(strEnvironment.c_str());
6597 AssertPtrBreakStmt(newEnvStr, vrc = vrc2);
6598
6599 /* put new variables to the environment
6600 * (ignore empty variable names here since RTEnv API
6601 * intentionally doesn't do that) */
6602 char *var = newEnvStr;
6603 for (char *p = newEnvStr; *p; ++p)
6604 {
6605 if (*p == '\n' && (p == newEnvStr || *(p - 1) != '\\'))
6606 {
6607 *p = '\0';
6608 if (*var)
6609 {
6610 char *val = strchr(var, '=');
6611 if (val)
6612 {
6613 *val++ = '\0';
6614 vrc2 = RTEnvSetEx(env, var, val);
6615 }
6616 else
6617 vrc2 = RTEnvUnsetEx(env, var);
6618 if (RT_FAILURE(vrc2))
6619 break;
6620 }
6621 var = p + 1;
6622 }
6623 }
6624 if (RT_SUCCESS(vrc2) && *var)
6625 vrc2 = RTEnvPutEx(env, var);
6626
6627 AssertRCBreakStmt(vrc2, vrc = vrc2);
6628 }
6629 while (0);
6630
6631 if (newEnvStr != NULL)
6632 RTStrFree(newEnvStr);
6633 }
6634
6635 /* Qt is default */
6636#ifdef VBOX_WITH_QTGUI
6637 if (strType == "gui" || strType == "GUI/Qt")
6638 {
6639# ifdef RT_OS_DARWIN /* Avoid Launch Services confusing this with the selector by using a helper app. */
6640 const char VirtualBox_exe[] = "../Resources/VirtualBoxVM.app/Contents/MacOS/VirtualBoxVM";
6641# else
6642 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
6643# endif
6644 Assert(sz >= sizeof(VirtualBox_exe));
6645 strcpy(cmd, VirtualBox_exe);
6646
6647 Utf8Str idStr = mData->mUuid.toString();
6648 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), "--no-startvm-errormsgbox", 0 };
6649 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6650 }
6651#else /* !VBOX_WITH_QTGUI */
6652 if (0)
6653 ;
6654#endif /* VBOX_WITH_QTGUI */
6655
6656 else
6657
6658#ifdef VBOX_WITH_VBOXSDL
6659 if (strType == "sdl" || strType == "GUI/SDL")
6660 {
6661 const char VBoxSDL_exe[] = "VBoxSDL" HOSTSUFF_EXE;
6662 Assert(sz >= sizeof(VBoxSDL_exe));
6663 strcpy(cmd, VBoxSDL_exe);
6664
6665 Utf8Str idStr = mData->mUuid.toString();
6666 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(), "--startvm", idStr.c_str(), 0 };
6667 fprintf(stderr, "SDL=%s\n", szPath);
6668 vrc = RTProcCreate(szPath, args, env, 0, &pid);
6669 }
6670#else /* !VBOX_WITH_VBOXSDL */
6671 if (0)
6672 ;
6673#endif /* !VBOX_WITH_VBOXSDL */
6674
6675 else
6676
6677#ifdef VBOX_WITH_HEADLESS
6678 if ( strType == "headless"
6679 || strType == "capture"
6680 || strType == "vrdp" /* Deprecated. Same as headless. */
6681 )
6682 {
6683 /* On pre-4.0 the "headless" type was used for passing "--vrdp off" to VBoxHeadless to let it work in OSE,
6684 * which did not contain VRDP server. In VBox 4.0 the remote desktop server (VRDE) is optional,
6685 * and a VM works even if the server has not been installed.
6686 * So in 4.0 the "headless" behavior remains the same for default VBox installations.
6687 * Only if a VRDE has been installed and the VM enables it, the "headless" will work
6688 * differently in 4.0 and 3.x.
6689 */
6690 const char VBoxHeadless_exe[] = "VBoxHeadless" HOSTSUFF_EXE;
6691 Assert(sz >= sizeof(VBoxHeadless_exe));
6692 strcpy(cmd, VBoxHeadless_exe);
6693
6694 Utf8Str idStr = mData->mUuid.toString();
6695 /* Leave space for "--capture" arg. */
6696 const char * args[] = {szPath, "--comment", mUserData->s.strName.c_str(),
6697 "--startvm", idStr.c_str(),
6698 "--vrde", "config",
6699 0, /* For "--capture". */
6700 0 };
6701 if (strType == "capture")
6702 {
6703 unsigned pos = RT_ELEMENTS(args) - 2;
6704 args[pos] = "--capture";
6705 }
6706 vrc = RTProcCreate(szPath, args, env,
6707#ifdef RT_OS_WINDOWS
6708 RTPROC_FLAGS_NO_WINDOW
6709#else
6710 0
6711#endif
6712 , &pid);
6713 }
6714#else /* !VBOX_WITH_HEADLESS */
6715 if (0)
6716 ;
6717#endif /* !VBOX_WITH_HEADLESS */
6718 else
6719 {
6720 RTEnvDestroy(env);
6721 return setError(E_INVALIDARG,
6722 tr("Invalid session type: '%s'"),
6723 strType.c_str());
6724 }
6725
6726 RTEnvDestroy(env);
6727
6728 if (RT_FAILURE(vrc))
6729 return setError(VBOX_E_IPRT_ERROR,
6730 tr("Could not launch a process for the machine '%s' (%Rrc)"),
6731 mUserData->s.strName.c_str(), vrc);
6732
6733 LogFlowThisFunc(("launched.pid=%d(0x%x)\n", pid, pid));
6734
6735 /*
6736 * Note that we don't leave the lock here before calling the client,
6737 * because it doesn't need to call us back if called with a NULL argument.
6738 * Leaving the lock here is dangerous because we didn't prepare the
6739 * launch data yet, but the client we've just started may happen to be
6740 * too fast and call openSession() that will fail (because of PID, etc.),
6741 * so that the Machine will never get out of the Spawning session state.
6742 */
6743
6744 /* inform the session that it will be a remote one */
6745 LogFlowThisFunc(("Calling AssignMachine (NULL)...\n"));
6746 HRESULT rc = aControl->AssignMachine(NULL);
6747 LogFlowThisFunc(("AssignMachine (NULL) returned %08X\n", rc));
6748
6749 if (FAILED(rc))
6750 {
6751 /* restore the session state */
6752 mData->mSession.mState = SessionState_Unlocked;
6753 /* The failure may occur w/o any error info (from RPC), so provide one */
6754 return setError(VBOX_E_VM_ERROR,
6755 tr("Failed to assign the machine to the session (%Rrc)"), rc);
6756 }
6757
6758 /* attach launch data to the machine */
6759 Assert(mData->mSession.mPid == NIL_RTPROCESS);
6760 mData->mSession.mRemoteControls.push_back (aControl);
6761 mData->mSession.mProgress = aProgress;
6762 mData->mSession.mPid = pid;
6763 mData->mSession.mState = SessionState_Spawning;
6764 mData->mSession.mType = strType;
6765
6766 LogFlowThisFuncLeave();
6767 return S_OK;
6768}
6769
6770/**
6771 * Returns @c true if the given machine has an open direct session and returns
6772 * the session machine instance and additional session data (on some platforms)
6773 * if so.
6774 *
6775 * Note that when the method returns @c false, the arguments remain unchanged.
6776 *
6777 * @param aMachine Session machine object.
6778 * @param aControl Direct session control object (optional).
6779 * @param aIPCSem Mutex IPC semaphore handle for this machine (optional).
6780 *
6781 * @note locks this object for reading.
6782 */
6783#if defined(RT_OS_WINDOWS)
6784bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6785 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6786 HANDLE *aIPCSem /*= NULL*/,
6787 bool aAllowClosing /*= false*/)
6788#elif defined(RT_OS_OS2)
6789bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6790 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6791 HMTX *aIPCSem /*= NULL*/,
6792 bool aAllowClosing /*= false*/)
6793#else
6794bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
6795 ComPtr<IInternalSessionControl> *aControl /*= NULL*/,
6796 bool aAllowClosing /*= false*/)
6797#endif
6798{
6799 AutoLimitedCaller autoCaller(this);
6800 AssertComRCReturn(autoCaller.rc(), false);
6801
6802 /* just return false for inaccessible machines */
6803 if (autoCaller.state() != Ready)
6804 return false;
6805
6806 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6807
6808 if ( mData->mSession.mState == SessionState_Locked
6809 || (aAllowClosing && mData->mSession.mState == SessionState_Unlocking)
6810 )
6811 {
6812 AssertReturn(!mData->mSession.mMachine.isNull(), false);
6813
6814 aMachine = mData->mSession.mMachine;
6815
6816 if (aControl != NULL)
6817 *aControl = mData->mSession.mDirectControl;
6818
6819#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6820 /* Additional session data */
6821 if (aIPCSem != NULL)
6822 *aIPCSem = aMachine->mIPCSem;
6823#endif
6824 return true;
6825 }
6826
6827 return false;
6828}
6829
6830/**
6831 * Returns @c true if the given machine has an spawning direct session and
6832 * returns and additional session data (on some platforms) if so.
6833 *
6834 * Note that when the method returns @c false, the arguments remain unchanged.
6835 *
6836 * @param aPID PID of the spawned direct session process.
6837 *
6838 * @note locks this object for reading.
6839 */
6840#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6841bool Machine::isSessionSpawning(RTPROCESS *aPID /*= NULL*/)
6842#else
6843bool Machine::isSessionSpawning()
6844#endif
6845{
6846 AutoLimitedCaller autoCaller(this);
6847 AssertComRCReturn(autoCaller.rc(), false);
6848
6849 /* just return false for inaccessible machines */
6850 if (autoCaller.state() != Ready)
6851 return false;
6852
6853 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6854
6855 if (mData->mSession.mState == SessionState_Spawning)
6856 {
6857#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6858 /* Additional session data */
6859 if (aPID != NULL)
6860 {
6861 AssertReturn(mData->mSession.mPid != NIL_RTPROCESS, false);
6862 *aPID = mData->mSession.mPid;
6863 }
6864#endif
6865 return true;
6866 }
6867
6868 return false;
6869}
6870
6871/**
6872 * Called from the client watcher thread to check for unexpected client process
6873 * death during Session_Spawning state (e.g. before it successfully opened a
6874 * direct session).
6875 *
6876 * On Win32 and on OS/2, this method is called only when we've got the
6877 * direct client's process termination notification, so it always returns @c
6878 * true.
6879 *
6880 * On other platforms, this method returns @c true if the client process is
6881 * terminated and @c false if it's still alive.
6882 *
6883 * @note Locks this object for writing.
6884 */
6885bool Machine::checkForSpawnFailure()
6886{
6887 AutoCaller autoCaller(this);
6888 if (!autoCaller.isOk())
6889 {
6890 /* nothing to do */
6891 LogFlowThisFunc(("Already uninitialized!\n"));
6892 return true;
6893 }
6894
6895 /* VirtualBox::addProcessToReap() needs a write lock */
6896 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
6897
6898 if (mData->mSession.mState != SessionState_Spawning)
6899 {
6900 /* nothing to do */
6901 LogFlowThisFunc(("Not spawning any more!\n"));
6902 return true;
6903 }
6904
6905 HRESULT rc = S_OK;
6906
6907#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
6908
6909 /* the process was already unexpectedly terminated, we just need to set an
6910 * error and finalize session spawning */
6911 rc = setError(E_FAIL,
6912 tr("The virtual machine '%s' has terminated unexpectedly during startup"),
6913 getName().c_str());
6914#else
6915
6916 /* PID not yet initialized, skip check. */
6917 if (mData->mSession.mPid == NIL_RTPROCESS)
6918 return false;
6919
6920 RTPROCSTATUS status;
6921 int vrc = ::RTProcWait(mData->mSession.mPid, RTPROCWAIT_FLAGS_NOBLOCK,
6922 &status);
6923
6924 if (vrc != VERR_PROCESS_RUNNING)
6925 {
6926 if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_NORMAL)
6927 rc = setError(E_FAIL,
6928 tr("The virtual machine '%s' has terminated unexpectedly during startup with exit code %d"),
6929 getName().c_str(), status.iStatus);
6930 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_SIGNAL)
6931 rc = setError(E_FAIL,
6932 tr("The virtual machine '%s' has terminated unexpectedly during startup because of signal %d"),
6933 getName().c_str(), status.iStatus);
6934 else if (RT_SUCCESS(vrc) && status.enmReason == RTPROCEXITREASON_ABEND)
6935 rc = setError(E_FAIL,
6936 tr("The virtual machine '%s' has terminated abnormally"),
6937 getName().c_str(), status.iStatus);
6938 else
6939 rc = setError(E_FAIL,
6940 tr("The virtual machine '%s' has terminated unexpectedly during startup (%Rrc)"),
6941 getName().c_str(), rc);
6942 }
6943
6944#endif
6945
6946 if (FAILED(rc))
6947 {
6948 /* Close the remote session, remove the remote control from the list
6949 * and reset session state to Closed (@note keep the code in sync with
6950 * the relevant part in checkForSpawnFailure()). */
6951
6952 Assert(mData->mSession.mRemoteControls.size() == 1);
6953 if (mData->mSession.mRemoteControls.size() == 1)
6954 {
6955 ErrorInfoKeeper eik;
6956 mData->mSession.mRemoteControls.front()->Uninitialize();
6957 }
6958
6959 mData->mSession.mRemoteControls.clear();
6960 mData->mSession.mState = SessionState_Unlocked;
6961
6962 /* finalize the progress after setting the state */
6963 if (!mData->mSession.mProgress.isNull())
6964 {
6965 mData->mSession.mProgress->notifyComplete(rc);
6966 mData->mSession.mProgress.setNull();
6967 }
6968
6969 mParent->addProcessToReap(mData->mSession.mPid);
6970 mData->mSession.mPid = NIL_RTPROCESS;
6971
6972 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
6973 return true;
6974 }
6975
6976 return false;
6977}
6978
6979/**
6980 * Checks whether the machine can be registered. If so, commits and saves
6981 * all settings.
6982 *
6983 * @note Must be called from mParent's write lock. Locks this object and
6984 * children for writing.
6985 */
6986HRESULT Machine::prepareRegister()
6987{
6988 AssertReturn(mParent->isWriteLockOnCurrentThread(), E_FAIL);
6989
6990 AutoLimitedCaller autoCaller(this);
6991 AssertComRCReturnRC(autoCaller.rc());
6992
6993 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6994
6995 /* wait for state dependents to drop to zero */
6996 ensureNoStateDependencies();
6997
6998 if (!mData->mAccessible)
6999 return setError(VBOX_E_INVALID_OBJECT_STATE,
7000 tr("The machine '%s' with UUID {%s} is inaccessible and cannot be registered"),
7001 mUserData->s.strName.c_str(),
7002 mData->mUuid.toString().c_str());
7003
7004 AssertReturn(autoCaller.state() == Ready, E_FAIL);
7005
7006 if (mData->mRegistered)
7007 return setError(VBOX_E_INVALID_OBJECT_STATE,
7008 tr("The machine '%s' with UUID {%s} is already registered"),
7009 mUserData->s.strName.c_str(),
7010 mData->mUuid.toString().c_str());
7011
7012 HRESULT rc = S_OK;
7013
7014 // Ensure the settings are saved. If we are going to be registered and
7015 // no config file exists yet, create it by calling saveSettings() too.
7016 if ( (mData->flModifications)
7017 || (!mData->pMachineConfigFile->fileExists())
7018 )
7019 {
7020 rc = saveSettings(NULL);
7021 // no need to check whether VirtualBox.xml needs saving too since
7022 // we can't have a machine XML file rename pending
7023 if (FAILED(rc)) return rc;
7024 }
7025
7026 /* more config checking goes here */
7027
7028 if (SUCCEEDED(rc))
7029 {
7030 /* we may have had implicit modifications we want to fix on success */
7031 commit();
7032
7033 mData->mRegistered = true;
7034 }
7035 else
7036 {
7037 /* we may have had implicit modifications we want to cancel on failure*/
7038 rollback(false /* aNotify */);
7039 }
7040
7041 return rc;
7042}
7043
7044/**
7045 * Increases the number of objects dependent on the machine state or on the
7046 * registered state. Guarantees that these two states will not change at least
7047 * until #releaseStateDependency() is called.
7048 *
7049 * Depending on the @a aDepType value, additional state checks may be made.
7050 * These checks will set extended error info on failure. See
7051 * #checkStateDependency() for more info.
7052 *
7053 * If this method returns a failure, the dependency is not added and the caller
7054 * is not allowed to rely on any particular machine state or registration state
7055 * value and may return the failed result code to the upper level.
7056 *
7057 * @param aDepType Dependency type to add.
7058 * @param aState Current machine state (NULL if not interested).
7059 * @param aRegistered Current registered state (NULL if not interested).
7060 *
7061 * @note Locks this object for writing.
7062 */
7063HRESULT Machine::addStateDependency(StateDependency aDepType /* = AnyStateDep */,
7064 MachineState_T *aState /* = NULL */,
7065 BOOL *aRegistered /* = NULL */)
7066{
7067 AutoCaller autoCaller(this);
7068 AssertComRCReturnRC(autoCaller.rc());
7069
7070 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7071
7072 HRESULT rc = checkStateDependency(aDepType);
7073 if (FAILED(rc)) return rc;
7074
7075 {
7076 if (mData->mMachineStateChangePending != 0)
7077 {
7078 /* ensureNoStateDependencies() is waiting for state dependencies to
7079 * drop to zero so don't add more. It may make sense to wait a bit
7080 * and retry before reporting an error (since the pending state
7081 * transition should be really quick) but let's just assert for
7082 * now to see if it ever happens on practice. */
7083
7084 AssertFailed();
7085
7086 return setError(E_ACCESSDENIED,
7087 tr("Machine state change is in progress. Please retry the operation later."));
7088 }
7089
7090 ++mData->mMachineStateDeps;
7091 Assert(mData->mMachineStateDeps != 0 /* overflow */);
7092 }
7093
7094 if (aState)
7095 *aState = mData->mMachineState;
7096 if (aRegistered)
7097 *aRegistered = mData->mRegistered;
7098
7099 return S_OK;
7100}
7101
7102/**
7103 * Decreases the number of objects dependent on the machine state.
7104 * Must always complete the #addStateDependency() call after the state
7105 * dependency is no more necessary.
7106 */
7107void Machine::releaseStateDependency()
7108{
7109 AutoCaller autoCaller(this);
7110 AssertComRCReturnVoid(autoCaller.rc());
7111
7112 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7113
7114 /* releaseStateDependency() w/o addStateDependency()? */
7115 AssertReturnVoid(mData->mMachineStateDeps != 0);
7116 -- mData->mMachineStateDeps;
7117
7118 if (mData->mMachineStateDeps == 0)
7119 {
7120 /* inform ensureNoStateDependencies() that there are no more deps */
7121 if (mData->mMachineStateChangePending != 0)
7122 {
7123 Assert(mData->mMachineStateDepsSem != NIL_RTSEMEVENTMULTI);
7124 RTSemEventMultiSignal (mData->mMachineStateDepsSem);
7125 }
7126 }
7127}
7128
7129// protected methods
7130/////////////////////////////////////////////////////////////////////////////
7131
7132/**
7133 * Performs machine state checks based on the @a aDepType value. If a check
7134 * fails, this method will set extended error info, otherwise it will return
7135 * S_OK. It is supposed, that on failure, the caller will immediately return
7136 * the return value of this method to the upper level.
7137 *
7138 * When @a aDepType is AnyStateDep, this method always returns S_OK.
7139 *
7140 * When @a aDepType is MutableStateDep, this method returns S_OK only if the
7141 * current state of this machine object allows to change settings of the
7142 * machine (i.e. the machine is not registered, or registered but not running
7143 * and not saved). It is useful to call this method from Machine setters
7144 * before performing any change.
7145 *
7146 * When @a aDepType is MutableOrSavedStateDep, this method behaves the same
7147 * as for MutableStateDep except that if the machine is saved, S_OK is also
7148 * returned. This is useful in setters which allow changing machine
7149 * properties when it is in the saved state.
7150 *
7151 * @param aDepType Dependency type to check.
7152 *
7153 * @note Non Machine based classes should use #addStateDependency() and
7154 * #releaseStateDependency() methods or the smart AutoStateDependency
7155 * template.
7156 *
7157 * @note This method must be called from under this object's read or write
7158 * lock.
7159 */
7160HRESULT Machine::checkStateDependency(StateDependency aDepType)
7161{
7162 switch (aDepType)
7163 {
7164 case AnyStateDep:
7165 {
7166 break;
7167 }
7168 case MutableStateDep:
7169 {
7170 if ( mData->mRegistered
7171 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7172 || ( mData->mMachineState != MachineState_Paused
7173 && mData->mMachineState != MachineState_Running
7174 && mData->mMachineState != MachineState_Aborted
7175 && mData->mMachineState != MachineState_Teleported
7176 && mData->mMachineState != MachineState_PoweredOff
7177 )
7178 )
7179 )
7180 return setError(VBOX_E_INVALID_VM_STATE,
7181 tr("The machine is not mutable (state is %s)"),
7182 Global::stringifyMachineState(mData->mMachineState));
7183 break;
7184 }
7185 case MutableOrSavedStateDep:
7186 {
7187 if ( mData->mRegistered
7188 && ( !isSessionMachine() /** @todo This was just converted raw; Check if Running and Paused should actually be included here... (Live Migration) */
7189 || ( mData->mMachineState != MachineState_Paused
7190 && mData->mMachineState != MachineState_Running
7191 && mData->mMachineState != MachineState_Aborted
7192 && mData->mMachineState != MachineState_Teleported
7193 && mData->mMachineState != MachineState_Saved
7194 && mData->mMachineState != MachineState_PoweredOff
7195 )
7196 )
7197 )
7198 return setError(VBOX_E_INVALID_VM_STATE,
7199 tr("The machine is not mutable (state is %s)"),
7200 Global::stringifyMachineState(mData->mMachineState));
7201 break;
7202 }
7203 }
7204
7205 return S_OK;
7206}
7207
7208/**
7209 * Helper to initialize all associated child objects and allocate data
7210 * structures.
7211 *
7212 * This method must be called as a part of the object's initialization procedure
7213 * (usually done in the #init() method).
7214 *
7215 * @note Must be called only from #init() or from #registeredInit().
7216 */
7217HRESULT Machine::initDataAndChildObjects()
7218{
7219 AutoCaller autoCaller(this);
7220 AssertComRCReturnRC(autoCaller.rc());
7221 AssertComRCReturn(autoCaller.state() == InInit ||
7222 autoCaller.state() == Limited, E_FAIL);
7223
7224 AssertReturn(!mData->mAccessible, E_FAIL);
7225
7226 /* allocate data structures */
7227 mSSData.allocate();
7228 mUserData.allocate();
7229 mHWData.allocate();
7230 mMediaData.allocate();
7231 mStorageControllers.allocate();
7232
7233 /* initialize mOSTypeId */
7234 mUserData->s.strOsType = mParent->getUnknownOSType()->id();
7235
7236 /* create associated BIOS settings object */
7237 unconst(mBIOSSettings).createObject();
7238 mBIOSSettings->init(this);
7239
7240 /* create an associated VRDE object (default is disabled) */
7241 unconst(mVRDEServer).createObject();
7242 mVRDEServer->init(this);
7243
7244 /* create associated serial port objects */
7245 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7246 {
7247 unconst(mSerialPorts[slot]).createObject();
7248 mSerialPorts[slot]->init(this, slot);
7249 }
7250
7251 /* create associated parallel port objects */
7252 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7253 {
7254 unconst(mParallelPorts[slot]).createObject();
7255 mParallelPorts[slot]->init(this, slot);
7256 }
7257
7258 /* create the audio adapter object (always present, default is disabled) */
7259 unconst(mAudioAdapter).createObject();
7260 mAudioAdapter->init(this);
7261
7262 /* create the USB controller object (always present, default is disabled) */
7263 unconst(mUSBController).createObject();
7264 mUSBController->init(this);
7265
7266 /* create associated network adapter objects */
7267 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot ++)
7268 {
7269 unconst(mNetworkAdapters[slot]).createObject();
7270 mNetworkAdapters[slot]->init(this, slot);
7271 }
7272
7273 /* create the bandwidth control */
7274 unconst(mBandwidthControl).createObject();
7275 mBandwidthControl->init(this);
7276
7277 return S_OK;
7278}
7279
7280/**
7281 * Helper to uninitialize all associated child objects and to free all data
7282 * structures.
7283 *
7284 * This method must be called as a part of the object's uninitialization
7285 * procedure (usually done in the #uninit() method).
7286 *
7287 * @note Must be called only from #uninit() or from #registeredInit().
7288 */
7289void Machine::uninitDataAndChildObjects()
7290{
7291 AutoCaller autoCaller(this);
7292 AssertComRCReturnVoid(autoCaller.rc());
7293 AssertComRCReturnVoid( autoCaller.state() == InUninit
7294 || autoCaller.state() == Limited);
7295
7296 /* tell all our other child objects we've been uninitialized */
7297 if (mBandwidthControl)
7298 {
7299 mBandwidthControl->uninit();
7300 unconst(mBandwidthControl).setNull();
7301 }
7302
7303 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
7304 {
7305 if (mNetworkAdapters[slot])
7306 {
7307 mNetworkAdapters[slot]->uninit();
7308 unconst(mNetworkAdapters[slot]).setNull();
7309 }
7310 }
7311
7312 if (mUSBController)
7313 {
7314 mUSBController->uninit();
7315 unconst(mUSBController).setNull();
7316 }
7317
7318 if (mAudioAdapter)
7319 {
7320 mAudioAdapter->uninit();
7321 unconst(mAudioAdapter).setNull();
7322 }
7323
7324 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
7325 {
7326 if (mParallelPorts[slot])
7327 {
7328 mParallelPorts[slot]->uninit();
7329 unconst(mParallelPorts[slot]).setNull();
7330 }
7331 }
7332
7333 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
7334 {
7335 if (mSerialPorts[slot])
7336 {
7337 mSerialPorts[slot]->uninit();
7338 unconst(mSerialPorts[slot]).setNull();
7339 }
7340 }
7341
7342 if (mVRDEServer)
7343 {
7344 mVRDEServer->uninit();
7345 unconst(mVRDEServer).setNull();
7346 }
7347
7348 if (mBIOSSettings)
7349 {
7350 mBIOSSettings->uninit();
7351 unconst(mBIOSSettings).setNull();
7352 }
7353
7354 /* Deassociate hard disks (only when a real Machine or a SnapshotMachine
7355 * instance is uninitialized; SessionMachine instances refer to real
7356 * Machine hard disks). This is necessary for a clean re-initialization of
7357 * the VM after successfully re-checking the accessibility state. Note
7358 * that in case of normal Machine or SnapshotMachine uninitialization (as
7359 * a result of unregistering or deleting the snapshot), outdated hard
7360 * disk attachments will already be uninitialized and deleted, so this
7361 * code will not affect them. */
7362 if ( !!mMediaData
7363 && (!isSessionMachine())
7364 )
7365 {
7366 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
7367 it != mMediaData->mAttachments.end();
7368 ++it)
7369 {
7370 ComObjPtr<Medium> hd = (*it)->getMedium();
7371 if (hd.isNull())
7372 continue;
7373 HRESULT rc = hd->removeBackReference(mData->mUuid, getSnapshotId());
7374 AssertComRC(rc);
7375 }
7376 }
7377
7378 if (!isSessionMachine() && !isSnapshotMachine())
7379 {
7380 // clean up the snapshots list (Snapshot::uninit() will handle the snapshot's children recursively)
7381 if (mData->mFirstSnapshot)
7382 {
7383 // snapshots tree is protected by media write lock; strictly
7384 // this isn't necessary here since we're deleting the entire
7385 // machine, but otherwise we assert in Snapshot::uninit()
7386 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7387 mData->mFirstSnapshot->uninit();
7388 mData->mFirstSnapshot.setNull();
7389 }
7390
7391 mData->mCurrentSnapshot.setNull();
7392 }
7393
7394 /* free data structures (the essential mData structure is not freed here
7395 * since it may be still in use) */
7396 mMediaData.free();
7397 mStorageControllers.free();
7398 mHWData.free();
7399 mUserData.free();
7400 mSSData.free();
7401}
7402
7403/**
7404 * Returns a pointer to the Machine object for this machine that acts like a
7405 * parent for complex machine data objects such as shared folders, etc.
7406 *
7407 * For primary Machine objects and for SnapshotMachine objects, returns this
7408 * object's pointer itself. For SessionMachine objects, returns the peer
7409 * (primary) machine pointer.
7410 */
7411Machine* Machine::getMachine()
7412{
7413 if (isSessionMachine())
7414 return (Machine*)mPeer;
7415 return this;
7416}
7417
7418/**
7419 * Makes sure that there are no machine state dependents. If necessary, waits
7420 * for the number of dependents to drop to zero.
7421 *
7422 * Make sure this method is called from under this object's write lock to
7423 * guarantee that no new dependents may be added when this method returns
7424 * control to the caller.
7425 *
7426 * @note Locks this object for writing. The lock will be released while waiting
7427 * (if necessary).
7428 *
7429 * @warning To be used only in methods that change the machine state!
7430 */
7431void Machine::ensureNoStateDependencies()
7432{
7433 AssertReturnVoid(isWriteLockOnCurrentThread());
7434
7435 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7436
7437 /* Wait for all state dependents if necessary */
7438 if (mData->mMachineStateDeps != 0)
7439 {
7440 /* lazy semaphore creation */
7441 if (mData->mMachineStateDepsSem == NIL_RTSEMEVENTMULTI)
7442 RTSemEventMultiCreate(&mData->mMachineStateDepsSem);
7443
7444 LogFlowThisFunc(("Waiting for state deps (%d) to drop to zero...\n",
7445 mData->mMachineStateDeps));
7446
7447 ++mData->mMachineStateChangePending;
7448
7449 /* reset the semaphore before waiting, the last dependent will signal
7450 * it */
7451 RTSemEventMultiReset(mData->mMachineStateDepsSem);
7452
7453 alock.leave();
7454
7455 RTSemEventMultiWait(mData->mMachineStateDepsSem, RT_INDEFINITE_WAIT);
7456
7457 alock.enter();
7458
7459 -- mData->mMachineStateChangePending;
7460 }
7461}
7462
7463/**
7464 * Changes the machine state and informs callbacks.
7465 *
7466 * This method is not intended to fail so it either returns S_OK or asserts (and
7467 * returns a failure).
7468 *
7469 * @note Locks this object for writing.
7470 */
7471HRESULT Machine::setMachineState(MachineState_T aMachineState)
7472{
7473 LogFlowThisFuncEnter();
7474 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
7475
7476 AutoCaller autoCaller(this);
7477 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
7478
7479 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7480
7481 /* wait for state dependents to drop to zero */
7482 ensureNoStateDependencies();
7483
7484 if (mData->mMachineState != aMachineState)
7485 {
7486 mData->mMachineState = aMachineState;
7487
7488 RTTimeNow(&mData->mLastStateChange);
7489
7490 mParent->onMachineStateChange(mData->mUuid, aMachineState);
7491 }
7492
7493 LogFlowThisFuncLeave();
7494 return S_OK;
7495}
7496
7497/**
7498 * Searches for a shared folder with the given logical name
7499 * in the collection of shared folders.
7500 *
7501 * @param aName logical name of the shared folder
7502 * @param aSharedFolder where to return the found object
7503 * @param aSetError whether to set the error info if the folder is
7504 * not found
7505 * @return
7506 * S_OK when found or VBOX_E_OBJECT_NOT_FOUND when not found
7507 *
7508 * @note
7509 * must be called from under the object's lock!
7510 */
7511HRESULT Machine::findSharedFolder(const Utf8Str &aName,
7512 ComObjPtr<SharedFolder> &aSharedFolder,
7513 bool aSetError /* = false */)
7514{
7515 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
7516 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
7517 it != mHWData->mSharedFolders.end();
7518 ++it)
7519 {
7520 SharedFolder *pSF = *it;
7521 AutoCaller autoCaller(pSF);
7522 if (pSF->getName() == aName)
7523 {
7524 aSharedFolder = pSF;
7525 rc = S_OK;
7526 break;
7527 }
7528 }
7529
7530 if (aSetError && FAILED(rc))
7531 setError(rc, tr("Could not find a shared folder named '%s'"), aName.c_str());
7532
7533 return rc;
7534}
7535
7536/**
7537 * Initializes all machine instance data from the given settings structures
7538 * from XML. The exception is the machine UUID which needs special handling
7539 * depending on the caller's use case, so the caller needs to set that herself.
7540 *
7541 * This gets called in several contexts during machine initialization:
7542 *
7543 * -- When machine XML exists on disk already and needs to be loaded into memory,
7544 * for example, from registeredInit() to load all registered machines on
7545 * VirtualBox startup. In this case, puuidRegistry is NULL because the media
7546 * attached to the machine should be part of some media registry already.
7547 *
7548 * -- During OVF import, when a machine config has been constructed from an
7549 * OVF file. In this case, puuidRegistry is set to the machine UUID to
7550 * ensure that the media listed as attachments in the config (which have
7551 * been imported from the OVF) receive the correct registry ID.
7552 *
7553 * -- During VM cloning.
7554 *
7555 * @param config Machine settings from XML.
7556 * @param puuidRegistry If != NULL, Medium::setRegistryIdIfFirst() gets called with this registry ID for each attached medium in the config.
7557 * @return
7558 */
7559HRESULT Machine::loadMachineDataFromSettings(const settings::MachineConfigFile &config,
7560 const Guid *puuidRegistry)
7561{
7562 // copy name, description, OS type, teleporter, UTC etc.
7563 mUserData->s = config.machineUserData;
7564
7565 // look up the object by Id to check it is valid
7566 ComPtr<IGuestOSType> guestOSType;
7567 HRESULT rc = mParent->GetGuestOSType(Bstr(mUserData->s.strOsType).raw(),
7568 guestOSType.asOutParam());
7569 if (FAILED(rc)) return rc;
7570
7571 // stateFile (optional)
7572 if (config.strStateFile.isEmpty())
7573 mSSData->strStateFilePath.setNull();
7574 else
7575 {
7576 Utf8Str stateFilePathFull(config.strStateFile);
7577 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
7578 if (RT_FAILURE(vrc))
7579 return setError(E_FAIL,
7580 tr("Invalid saved state file path '%s' (%Rrc)"),
7581 config.strStateFile.c_str(),
7582 vrc);
7583 mSSData->strStateFilePath = stateFilePathFull;
7584 }
7585
7586 // snapshot folder needs special processing so set it again
7587 rc = COMSETTER(SnapshotFolder)(Bstr(config.machineUserData.strSnapshotFolder).raw());
7588 if (FAILED(rc)) return rc;
7589
7590 /* Copy the extra data items (Not in any case config is already the same as
7591 * mData->pMachineConfigFile, like when the xml files are read from disk. So
7592 * make sure the extra data map is copied). */
7593 mData->pMachineConfigFile->mapExtraDataItems = config.mapExtraDataItems;
7594
7595 /* currentStateModified (optional, default is true) */
7596 mData->mCurrentStateModified = config.fCurrentStateModified;
7597
7598 mData->mLastStateChange = config.timeLastStateChange;
7599
7600 /*
7601 * note: all mUserData members must be assigned prior this point because
7602 * we need to commit changes in order to let mUserData be shared by all
7603 * snapshot machine instances.
7604 */
7605 mUserData.commitCopy();
7606
7607 // machine registry, if present (must be loaded before snapshots)
7608 if (config.canHaveOwnMediaRegistry())
7609 {
7610 // determine machine folder
7611 Utf8Str strMachineFolder = getSettingsFileFull();
7612 strMachineFolder.stripFilename();
7613 rc = mParent->initMedia(getId(), // media registry ID == machine UUID
7614 config.mediaRegistry,
7615 strMachineFolder);
7616 if (FAILED(rc)) return rc;
7617 }
7618
7619 /* Snapshot node (optional) */
7620 size_t cRootSnapshots;
7621 if ((cRootSnapshots = config.llFirstSnapshot.size()))
7622 {
7623 // there must be only one root snapshot
7624 Assert(cRootSnapshots == 1);
7625
7626 const settings::Snapshot &snap = config.llFirstSnapshot.front();
7627
7628 rc = loadSnapshot(snap,
7629 config.uuidCurrentSnapshot,
7630 NULL); // no parent == first snapshot
7631 if (FAILED(rc)) return rc;
7632 }
7633
7634 // hardware data
7635 rc = loadHardware(config.hardwareMachine);
7636 if (FAILED(rc)) return rc;
7637
7638 // load storage controllers
7639 rc = loadStorageControllers(config.storageMachine,
7640 puuidRegistry,
7641 NULL /* puuidSnapshot */);
7642 if (FAILED(rc)) return rc;
7643
7644 /*
7645 * NOTE: the assignment below must be the last thing to do,
7646 * otherwise it will be not possible to change the settings
7647 * somewhere in the code above because all setters will be
7648 * blocked by checkStateDependency(MutableStateDep).
7649 */
7650
7651 /* set the machine state to Aborted or Saved when appropriate */
7652 if (config.fAborted)
7653 {
7654 mSSData->strStateFilePath.setNull();
7655
7656 /* no need to use setMachineState() during init() */
7657 mData->mMachineState = MachineState_Aborted;
7658 }
7659 else if (!mSSData->strStateFilePath.isEmpty())
7660 {
7661 /* no need to use setMachineState() during init() */
7662 mData->mMachineState = MachineState_Saved;
7663 }
7664
7665 // after loading settings, we are no longer different from the XML on disk
7666 mData->flModifications = 0;
7667
7668 return S_OK;
7669}
7670
7671/**
7672 * Recursively loads all snapshots starting from the given.
7673 *
7674 * @param aNode <Snapshot> node.
7675 * @param aCurSnapshotId Current snapshot ID from the settings file.
7676 * @param aParentSnapshot Parent snapshot.
7677 */
7678HRESULT Machine::loadSnapshot(const settings::Snapshot &data,
7679 const Guid &aCurSnapshotId,
7680 Snapshot *aParentSnapshot)
7681{
7682 AssertReturn(!isSnapshotMachine(), E_FAIL);
7683 AssertReturn(!isSessionMachine(), E_FAIL);
7684
7685 HRESULT rc = S_OK;
7686
7687 Utf8Str strStateFile;
7688 if (!data.strStateFile.isEmpty())
7689 {
7690 /* optional */
7691 strStateFile = data.strStateFile;
7692 int vrc = calculateFullPath(strStateFile, strStateFile);
7693 if (RT_FAILURE(vrc))
7694 return setError(E_FAIL,
7695 tr("Invalid saved state file path '%s' (%Rrc)"),
7696 strStateFile.c_str(),
7697 vrc);
7698 }
7699
7700 /* create a snapshot machine object */
7701 ComObjPtr<SnapshotMachine> pSnapshotMachine;
7702 pSnapshotMachine.createObject();
7703 rc = pSnapshotMachine->init(this,
7704 data.hardware,
7705 data.storage,
7706 data.uuid.ref(),
7707 strStateFile);
7708 if (FAILED(rc)) return rc;
7709
7710 /* create a snapshot object */
7711 ComObjPtr<Snapshot> pSnapshot;
7712 pSnapshot.createObject();
7713 /* initialize the snapshot */
7714 rc = pSnapshot->init(mParent, // VirtualBox object
7715 data.uuid,
7716 data.strName,
7717 data.strDescription,
7718 data.timestamp,
7719 pSnapshotMachine,
7720 aParentSnapshot);
7721 if (FAILED(rc)) return rc;
7722
7723 /* memorize the first snapshot if necessary */
7724 if (!mData->mFirstSnapshot)
7725 mData->mFirstSnapshot = pSnapshot;
7726
7727 /* memorize the current snapshot when appropriate */
7728 if ( !mData->mCurrentSnapshot
7729 && pSnapshot->getId() == aCurSnapshotId
7730 )
7731 mData->mCurrentSnapshot = pSnapshot;
7732
7733 // now create the children
7734 for (settings::SnapshotsList::const_iterator it = data.llChildSnapshots.begin();
7735 it != data.llChildSnapshots.end();
7736 ++it)
7737 {
7738 const settings::Snapshot &childData = *it;
7739 // recurse
7740 rc = loadSnapshot(childData,
7741 aCurSnapshotId,
7742 pSnapshot); // parent = the one we created above
7743 if (FAILED(rc)) return rc;
7744 }
7745
7746 return rc;
7747}
7748
7749/**
7750 * @param aNode <Hardware> node.
7751 */
7752HRESULT Machine::loadHardware(const settings::Hardware &data)
7753{
7754 AssertReturn(!isSessionMachine(), E_FAIL);
7755
7756 HRESULT rc = S_OK;
7757
7758 try
7759 {
7760 /* The hardware version attribute (optional). */
7761 mHWData->mHWVersion = data.strVersion;
7762 mHWData->mHardwareUUID = data.uuid;
7763
7764 mHWData->mHWVirtExEnabled = data.fHardwareVirt;
7765 mHWData->mHWVirtExExclusive = data.fHardwareVirtExclusive;
7766 mHWData->mHWVirtExNestedPagingEnabled = data.fNestedPaging;
7767 mHWData->mHWVirtExLargePagesEnabled = data.fLargePages;
7768 mHWData->mHWVirtExVPIDEnabled = data.fVPID;
7769 mHWData->mHWVirtExForceEnabled = data.fHardwareVirtForce;
7770 mHWData->mPAEEnabled = data.fPAE;
7771 mHWData->mSyntheticCpu = data.fSyntheticCpu;
7772
7773 mHWData->mCPUCount = data.cCPUs;
7774 mHWData->mCPUHotPlugEnabled = data.fCpuHotPlug;
7775 mHWData->mCpuExecutionCap = data.ulCpuExecutionCap;
7776
7777 // cpu
7778 if (mHWData->mCPUHotPlugEnabled)
7779 {
7780 for (settings::CpuList::const_iterator it = data.llCpus.begin();
7781 it != data.llCpus.end();
7782 ++it)
7783 {
7784 const settings::Cpu &cpu = *it;
7785
7786 mHWData->mCPUAttached[cpu.ulId] = true;
7787 }
7788 }
7789
7790 // cpuid leafs
7791 for (settings::CpuIdLeafsList::const_iterator it = data.llCpuIdLeafs.begin();
7792 it != data.llCpuIdLeafs.end();
7793 ++it)
7794 {
7795 const settings::CpuIdLeaf &leaf = *it;
7796
7797 switch (leaf.ulId)
7798 {
7799 case 0x0:
7800 case 0x1:
7801 case 0x2:
7802 case 0x3:
7803 case 0x4:
7804 case 0x5:
7805 case 0x6:
7806 case 0x7:
7807 case 0x8:
7808 case 0x9:
7809 case 0xA:
7810 mHWData->mCpuIdStdLeafs[leaf.ulId] = leaf;
7811 break;
7812
7813 case 0x80000000:
7814 case 0x80000001:
7815 case 0x80000002:
7816 case 0x80000003:
7817 case 0x80000004:
7818 case 0x80000005:
7819 case 0x80000006:
7820 case 0x80000007:
7821 case 0x80000008:
7822 case 0x80000009:
7823 case 0x8000000A:
7824 mHWData->mCpuIdExtLeafs[leaf.ulId - 0x80000000] = leaf;
7825 break;
7826
7827 default:
7828 /* just ignore */
7829 break;
7830 }
7831 }
7832
7833 mHWData->mMemorySize = data.ulMemorySizeMB;
7834 mHWData->mPageFusionEnabled = data.fPageFusionEnabled;
7835
7836 // boot order
7837 for (size_t i = 0;
7838 i < RT_ELEMENTS(mHWData->mBootOrder);
7839 i++)
7840 {
7841 settings::BootOrderMap::const_iterator it = data.mapBootOrder.find(i);
7842 if (it == data.mapBootOrder.end())
7843 mHWData->mBootOrder[i] = DeviceType_Null;
7844 else
7845 mHWData->mBootOrder[i] = it->second;
7846 }
7847
7848 mHWData->mVRAMSize = data.ulVRAMSizeMB;
7849 mHWData->mMonitorCount = data.cMonitors;
7850 mHWData->mAccelerate3DEnabled = data.fAccelerate3D;
7851 mHWData->mAccelerate2DVideoEnabled = data.fAccelerate2DVideo;
7852 mHWData->mFirmwareType = data.firmwareType;
7853 mHWData->mPointingHidType = data.pointingHidType;
7854 mHWData->mKeyboardHidType = data.keyboardHidType;
7855 mHWData->mChipsetType = data.chipsetType;
7856 mHWData->mHpetEnabled = data.fHpetEnabled;
7857
7858 /* VRDEServer */
7859 rc = mVRDEServer->loadSettings(data.vrdeSettings);
7860 if (FAILED(rc)) return rc;
7861
7862 /* BIOS */
7863 rc = mBIOSSettings->loadSettings(data.biosSettings);
7864 if (FAILED(rc)) return rc;
7865
7866 // Bandwidth control (must come before network adapters)
7867 rc = mBandwidthControl->loadSettings(data.ioSettings);
7868 if (FAILED(rc)) return rc;
7869
7870 /* USB Controller */
7871 rc = mUSBController->loadSettings(data.usbController);
7872 if (FAILED(rc)) return rc;
7873
7874 // network adapters
7875 for (settings::NetworkAdaptersList::const_iterator it = data.llNetworkAdapters.begin();
7876 it != data.llNetworkAdapters.end();
7877 ++it)
7878 {
7879 const settings::NetworkAdapter &nic = *it;
7880
7881 /* slot unicity is guaranteed by XML Schema */
7882 AssertBreak(nic.ulSlot < RT_ELEMENTS(mNetworkAdapters));
7883 rc = mNetworkAdapters[nic.ulSlot]->loadSettings(mBandwidthControl, nic);
7884 if (FAILED(rc)) return rc;
7885 }
7886
7887 // serial ports
7888 for (settings::SerialPortsList::const_iterator it = data.llSerialPorts.begin();
7889 it != data.llSerialPorts.end();
7890 ++it)
7891 {
7892 const settings::SerialPort &s = *it;
7893
7894 AssertBreak(s.ulSlot < RT_ELEMENTS(mSerialPorts));
7895 rc = mSerialPorts[s.ulSlot]->loadSettings(s);
7896 if (FAILED(rc)) return rc;
7897 }
7898
7899 // parallel ports (optional)
7900 for (settings::ParallelPortsList::const_iterator it = data.llParallelPorts.begin();
7901 it != data.llParallelPorts.end();
7902 ++it)
7903 {
7904 const settings::ParallelPort &p = *it;
7905
7906 AssertBreak(p.ulSlot < RT_ELEMENTS(mParallelPorts));
7907 rc = mParallelPorts[p.ulSlot]->loadSettings(p);
7908 if (FAILED(rc)) return rc;
7909 }
7910
7911 /* AudioAdapter */
7912 rc = mAudioAdapter->loadSettings(data.audioAdapter);
7913 if (FAILED(rc)) return rc;
7914
7915 /* Shared folders */
7916 for (settings::SharedFoldersList::const_iterator it = data.llSharedFolders.begin();
7917 it != data.llSharedFolders.end();
7918 ++it)
7919 {
7920 const settings::SharedFolder &sf = *it;
7921
7922 ComObjPtr<SharedFolder> sharedFolder;
7923 /* Check for double entries. Not allowed! */
7924 rc = findSharedFolder(sf.strName, sharedFolder, false /* aSetError */);
7925 if (SUCCEEDED(rc))
7926 return setError(VBOX_E_OBJECT_IN_USE,
7927 tr("Shared folder named '%s' already exists"),
7928 sf.strName.c_str());
7929
7930 /* Create the new shared folder. Don't break on error. This will be
7931 * reported when the machine starts. */
7932 sharedFolder.createObject();
7933 rc = sharedFolder->init(getMachine(),
7934 sf.strName,
7935 sf.strHostPath,
7936 RT_BOOL(sf.fWritable),
7937 RT_BOOL(sf.fAutoMount),
7938 false /* fFailOnError */);
7939 if (FAILED(rc)) return rc;
7940 mHWData->mSharedFolders.push_back(sharedFolder);
7941 }
7942
7943 // Clipboard
7944 mHWData->mClipboardMode = data.clipboardMode;
7945
7946 // guest settings
7947 mHWData->mMemoryBalloonSize = data.ulMemoryBalloonSize;
7948
7949 // IO settings
7950 mHWData->mIoCacheEnabled = data.ioSettings.fIoCacheEnabled;
7951 mHWData->mIoCacheSize = data.ioSettings.ulIoCacheSize;
7952
7953 // Host PCI devices
7954 for (settings::HostPciDeviceAttachmentList::const_iterator it = data.pciAttachments.begin();
7955 it != data.pciAttachments.end();
7956 ++it)
7957 {
7958 const settings::HostPciDeviceAttachment &hpda = *it;
7959 ComObjPtr<PciDeviceAttachment> pda;
7960
7961 pda.createObject();
7962 pda->loadSettings(this, hpda);
7963 mHWData->mPciDeviceAssignments.push_back(pda);
7964 }
7965
7966#ifdef VBOX_WITH_GUEST_PROPS
7967 /* Guest properties (optional) */
7968 for (settings::GuestPropertiesList::const_iterator it = data.llGuestProperties.begin();
7969 it != data.llGuestProperties.end();
7970 ++it)
7971 {
7972 const settings::GuestProperty &prop = *it;
7973 uint32_t fFlags = guestProp::NILFLAG;
7974 guestProp::validateFlags(prop.strFlags.c_str(), &fFlags);
7975 HWData::GuestProperty property = { prop.strName, prop.strValue, prop.timestamp, fFlags };
7976 mHWData->mGuestProperties.push_back(property);
7977 }
7978
7979 mHWData->mGuestPropertyNotificationPatterns = data.strNotificationPatterns;
7980#endif /* VBOX_WITH_GUEST_PROPS defined */
7981 }
7982 catch(std::bad_alloc &)
7983 {
7984 return E_OUTOFMEMORY;
7985 }
7986
7987 AssertComRC(rc);
7988 return rc;
7989}
7990
7991/**
7992 * Called from loadMachineDataFromSettings() for the storage controller data, including media.
7993 *
7994 * @param data
7995 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
7996 * @param puuidSnapshot
7997 * @return
7998 */
7999HRESULT Machine::loadStorageControllers(const settings::Storage &data,
8000 const Guid *puuidRegistry,
8001 const Guid *puuidSnapshot)
8002{
8003 AssertReturn(!isSessionMachine(), E_FAIL);
8004
8005 HRESULT rc = S_OK;
8006
8007 for (settings::StorageControllersList::const_iterator it = data.llStorageControllers.begin();
8008 it != data.llStorageControllers.end();
8009 ++it)
8010 {
8011 const settings::StorageController &ctlData = *it;
8012
8013 ComObjPtr<StorageController> pCtl;
8014 /* Try to find one with the name first. */
8015 rc = getStorageControllerByName(ctlData.strName, pCtl, false /* aSetError */);
8016 if (SUCCEEDED(rc))
8017 return setError(VBOX_E_OBJECT_IN_USE,
8018 tr("Storage controller named '%s' already exists"),
8019 ctlData.strName.c_str());
8020
8021 pCtl.createObject();
8022 rc = pCtl->init(this,
8023 ctlData.strName,
8024 ctlData.storageBus,
8025 ctlData.ulInstance,
8026 ctlData.fBootable);
8027 if (FAILED(rc)) return rc;
8028
8029 mStorageControllers->push_back(pCtl);
8030
8031 rc = pCtl->COMSETTER(ControllerType)(ctlData.controllerType);
8032 if (FAILED(rc)) return rc;
8033
8034 rc = pCtl->COMSETTER(PortCount)(ctlData.ulPortCount);
8035 if (FAILED(rc)) return rc;
8036
8037 rc = pCtl->COMSETTER(UseHostIOCache)(ctlData.fUseHostIOCache);
8038 if (FAILED(rc)) return rc;
8039
8040 /* Set IDE emulation settings (only for AHCI controller). */
8041 if (ctlData.controllerType == StorageControllerType_IntelAhci)
8042 {
8043 if ( (FAILED(rc = pCtl->SetIDEEmulationPort(0, ctlData.lIDE0MasterEmulationPort)))
8044 || (FAILED(rc = pCtl->SetIDEEmulationPort(1, ctlData.lIDE0SlaveEmulationPort)))
8045 || (FAILED(rc = pCtl->SetIDEEmulationPort(2, ctlData.lIDE1MasterEmulationPort)))
8046 || (FAILED(rc = pCtl->SetIDEEmulationPort(3, ctlData.lIDE1SlaveEmulationPort)))
8047 )
8048 return rc;
8049 }
8050
8051 /* Load the attached devices now. */
8052 rc = loadStorageDevices(pCtl,
8053 ctlData,
8054 puuidRegistry,
8055 puuidSnapshot);
8056 if (FAILED(rc)) return rc;
8057 }
8058
8059 return S_OK;
8060}
8061
8062/**
8063 * Called from loadStorageControllers for a controller's devices.
8064 *
8065 * @param aStorageController
8066 * @param data
8067 * @param puuidRegistry media registry ID to set media to or NULL; see Machine::loadMachineDataFromSettings()
8068 * @param aSnapshotId pointer to the snapshot ID if this is a snapshot machine
8069 * @return
8070 */
8071HRESULT Machine::loadStorageDevices(StorageController *aStorageController,
8072 const settings::StorageController &data,
8073 const Guid *puuidRegistry,
8074 const Guid *puuidSnapshot)
8075{
8076 HRESULT rc = S_OK;
8077
8078 /* paranoia: detect duplicate attachments */
8079 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8080 it != data.llAttachedDevices.end();
8081 ++it)
8082 {
8083 const settings::AttachedDevice &ad = *it;
8084
8085 for (settings::AttachedDevicesList::const_iterator it2 = it;
8086 it2 != data.llAttachedDevices.end();
8087 ++it2)
8088 {
8089 if (it == it2)
8090 continue;
8091
8092 const settings::AttachedDevice &ad2 = *it2;
8093
8094 if ( ad.lPort == ad2.lPort
8095 && ad.lDevice == ad2.lDevice)
8096 {
8097 return setError(E_FAIL,
8098 tr("Duplicate attachments for storage controller '%s', port %d, device %d of the virtual machine '%s'"),
8099 aStorageController->getName().c_str(),
8100 ad.lPort,
8101 ad.lDevice,
8102 mUserData->s.strName.c_str());
8103 }
8104 }
8105 }
8106
8107 for (settings::AttachedDevicesList::const_iterator it = data.llAttachedDevices.begin();
8108 it != data.llAttachedDevices.end();
8109 ++it)
8110 {
8111 const settings::AttachedDevice &dev = *it;
8112 ComObjPtr<Medium> medium;
8113
8114 switch (dev.deviceType)
8115 {
8116 case DeviceType_Floppy:
8117 case DeviceType_DVD:
8118 if (dev.strHostDriveSrc.isNotEmpty())
8119 rc = mParent->host()->findHostDriveByName(dev.deviceType, dev.strHostDriveSrc, false /* fRefresh */, medium);
8120 else
8121 rc = mParent->findRemoveableMedium(dev.deviceType,
8122 dev.uuid,
8123 false /* fRefresh */,
8124 false /* aSetError */,
8125 medium);
8126 if (rc == VBOX_E_OBJECT_NOT_FOUND)
8127 // This is not an error. The host drive or UUID might have vanished, so just go ahead without this removeable medium attachment
8128 rc = S_OK;
8129 break;
8130
8131 case DeviceType_HardDisk:
8132 {
8133 /* find a hard disk by UUID */
8134 rc = mParent->findHardDiskById(dev.uuid, true /* aDoSetError */, &medium);
8135 if (FAILED(rc))
8136 {
8137 if (isSnapshotMachine())
8138 {
8139 // wrap another error message around the "cannot find hard disk" set by findHardDisk
8140 // so the user knows that the bad disk is in a snapshot somewhere
8141 com::ErrorInfo info;
8142 return setError(E_FAIL,
8143 tr("A differencing image of snapshot {%RTuuid} could not be found. %ls"),
8144 puuidSnapshot->raw(),
8145 info.getText().raw());
8146 }
8147 else
8148 return rc;
8149 }
8150
8151 AutoWriteLock hdLock(medium COMMA_LOCKVAL_SRC_POS);
8152
8153 if (medium->getType() == MediumType_Immutable)
8154 {
8155 if (isSnapshotMachine())
8156 return setError(E_FAIL,
8157 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8158 "of the virtual machine '%s' ('%s')"),
8159 medium->getLocationFull().c_str(),
8160 dev.uuid.raw(),
8161 puuidSnapshot->raw(),
8162 mUserData->s.strName.c_str(),
8163 mData->m_strConfigFileFull.c_str());
8164
8165 return setError(E_FAIL,
8166 tr("Immutable hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8167 medium->getLocationFull().c_str(),
8168 dev.uuid.raw(),
8169 mUserData->s.strName.c_str(),
8170 mData->m_strConfigFileFull.c_str());
8171 }
8172
8173 if (medium->getType() == MediumType_MultiAttach)
8174 {
8175 if (isSnapshotMachine())
8176 return setError(E_FAIL,
8177 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to snapshot with UUID {%RTuuid} "
8178 "of the virtual machine '%s' ('%s')"),
8179 medium->getLocationFull().c_str(),
8180 dev.uuid.raw(),
8181 puuidSnapshot->raw(),
8182 mUserData->s.strName.c_str(),
8183 mData->m_strConfigFileFull.c_str());
8184
8185 return setError(E_FAIL,
8186 tr("Multi-attach hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s')"),
8187 medium->getLocationFull().c_str(),
8188 dev.uuid.raw(),
8189 mUserData->s.strName.c_str(),
8190 mData->m_strConfigFileFull.c_str());
8191 }
8192
8193 if ( !isSnapshotMachine()
8194 && medium->getChildren().size() != 0
8195 )
8196 return setError(E_FAIL,
8197 tr("Hard disk '%s' with UUID {%RTuuid} cannot be directly attached to the virtual machine '%s' ('%s') "
8198 "because it has %d differencing child hard disks"),
8199 medium->getLocationFull().c_str(),
8200 dev.uuid.raw(),
8201 mUserData->s.strName.c_str(),
8202 mData->m_strConfigFileFull.c_str(),
8203 medium->getChildren().size());
8204
8205 if (findAttachment(mMediaData->mAttachments,
8206 medium))
8207 return setError(E_FAIL,
8208 tr("Hard disk '%s' with UUID {%RTuuid} is already 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 break;
8215 }
8216
8217 default:
8218 return setError(E_FAIL,
8219 tr("Device '%s' with unknown type is attached to the virtual machine '%s' ('%s')"),
8220 medium->getLocationFull().c_str(),
8221 mUserData->s.strName.c_str(),
8222 mData->m_strConfigFileFull.c_str());
8223 }
8224
8225 if (FAILED(rc))
8226 break;
8227
8228 /* Bandwidth groups are loaded at this point. */
8229 ComObjPtr<BandwidthGroup> pBwGroup;
8230
8231 if (!dev.strBwGroup.isEmpty())
8232 {
8233 rc = mBandwidthControl->getBandwidthGroupByName(dev.strBwGroup, pBwGroup, false /* aSetError */);
8234 if (FAILED(rc))
8235 return setError(E_FAIL,
8236 tr("Device '%s' with unknown bandwidth group '%s' is attached to the virtual machine '%s' ('%s')"),
8237 medium->getLocationFull().c_str(),
8238 dev.strBwGroup.c_str(),
8239 mUserData->s.strName.c_str(),
8240 mData->m_strConfigFileFull.c_str());
8241 pBwGroup->reference();
8242 }
8243
8244 const Bstr controllerName = aStorageController->getName();
8245 ComObjPtr<MediumAttachment> pAttachment;
8246 pAttachment.createObject();
8247 rc = pAttachment->init(this,
8248 medium,
8249 controllerName,
8250 dev.lPort,
8251 dev.lDevice,
8252 dev.deviceType,
8253 false,
8254 dev.fPassThrough,
8255 dev.fTempEject,
8256 dev.fNonRotational,
8257 dev.fDiscard,
8258 pBwGroup.isNull() ? Utf8Str::Empty : pBwGroup->getName());
8259 if (FAILED(rc)) break;
8260
8261 /* associate the medium with this machine and snapshot */
8262 if (!medium.isNull())
8263 {
8264 AutoCaller medCaller(medium);
8265 if (FAILED(medCaller.rc())) return medCaller.rc();
8266 AutoWriteLock mlock(medium COMMA_LOCKVAL_SRC_POS);
8267
8268 if (isSnapshotMachine())
8269 rc = medium->addBackReference(mData->mUuid, *puuidSnapshot);
8270 else
8271 rc = medium->addBackReference(mData->mUuid);
8272 /* If the medium->addBackReference fails it sets an appropriate
8273 * error message, so no need to do any guesswork here. */
8274
8275 if (puuidRegistry)
8276 // caller wants registry ID to be set on all attached media (OVF import case)
8277 medium->addRegistry(*puuidRegistry, false /* fRecurse */);
8278 }
8279
8280 if (FAILED(rc))
8281 break;
8282
8283 /* back up mMediaData to let registeredInit() properly rollback on failure
8284 * (= limited accessibility) */
8285 setModified(IsModified_Storage);
8286 mMediaData.backup();
8287 mMediaData->mAttachments.push_back(pAttachment);
8288 }
8289
8290 return rc;
8291}
8292
8293/**
8294 * Returns the snapshot with the given UUID or fails of no such snapshot exists.
8295 *
8296 * @param aId snapshot UUID to find (empty UUID refers the first snapshot)
8297 * @param aSnapshot where to return the found snapshot
8298 * @param aSetError true to set extended error info on failure
8299 */
8300HRESULT Machine::findSnapshotById(const Guid &aId,
8301 ComObjPtr<Snapshot> &aSnapshot,
8302 bool aSetError /* = false */)
8303{
8304 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8305
8306 if (!mData->mFirstSnapshot)
8307 {
8308 if (aSetError)
8309 return setError(E_FAIL, tr("This machine does not have any snapshots"));
8310 return E_FAIL;
8311 }
8312
8313 if (aId.isEmpty())
8314 aSnapshot = mData->mFirstSnapshot;
8315 else
8316 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(aId.ref());
8317
8318 if (!aSnapshot)
8319 {
8320 if (aSetError)
8321 return setError(E_FAIL,
8322 tr("Could not find a snapshot with UUID {%s}"),
8323 aId.toString().c_str());
8324 return E_FAIL;
8325 }
8326
8327 return S_OK;
8328}
8329
8330/**
8331 * Returns the snapshot with the given name or fails of no such snapshot.
8332 *
8333 * @param aName snapshot name to find
8334 * @param aSnapshot where to return the found snapshot
8335 * @param aSetError true to set extended error info on failure
8336 */
8337HRESULT Machine::findSnapshotByName(const Utf8Str &strName,
8338 ComObjPtr<Snapshot> &aSnapshot,
8339 bool aSetError /* = false */)
8340{
8341 AssertReturn(!strName.isEmpty(), E_INVALIDARG);
8342
8343 AutoReadLock chlock(this COMMA_LOCKVAL_SRC_POS);
8344
8345 if (!mData->mFirstSnapshot)
8346 {
8347 if (aSetError)
8348 return setError(VBOX_E_OBJECT_NOT_FOUND,
8349 tr("This machine does not have any snapshots"));
8350 return VBOX_E_OBJECT_NOT_FOUND;
8351 }
8352
8353 aSnapshot = mData->mFirstSnapshot->findChildOrSelf(strName);
8354
8355 if (!aSnapshot)
8356 {
8357 if (aSetError)
8358 return setError(VBOX_E_OBJECT_NOT_FOUND,
8359 tr("Could not find a snapshot named '%s'"), strName.c_str());
8360 return VBOX_E_OBJECT_NOT_FOUND;
8361 }
8362
8363 return S_OK;
8364}
8365
8366/**
8367 * Returns a storage controller object with the given name.
8368 *
8369 * @param aName storage controller name to find
8370 * @param aStorageController where to return the found storage controller
8371 * @param aSetError true to set extended error info on failure
8372 */
8373HRESULT Machine::getStorageControllerByName(const Utf8Str &aName,
8374 ComObjPtr<StorageController> &aStorageController,
8375 bool aSetError /* = false */)
8376{
8377 AssertReturn(!aName.isEmpty(), E_INVALIDARG);
8378
8379 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
8380 it != mStorageControllers->end();
8381 ++it)
8382 {
8383 if ((*it)->getName() == aName)
8384 {
8385 aStorageController = (*it);
8386 return S_OK;
8387 }
8388 }
8389
8390 if (aSetError)
8391 return setError(VBOX_E_OBJECT_NOT_FOUND,
8392 tr("Could not find a storage controller named '%s'"),
8393 aName.c_str());
8394 return VBOX_E_OBJECT_NOT_FOUND;
8395}
8396
8397HRESULT Machine::getMediumAttachmentsOfController(CBSTR aName,
8398 MediaData::AttachmentList &atts)
8399{
8400 AutoCaller autoCaller(this);
8401 if (FAILED(autoCaller.rc())) return autoCaller.rc();
8402
8403 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8404
8405 for (MediaData::AttachmentList::iterator it = mMediaData->mAttachments.begin();
8406 it != mMediaData->mAttachments.end();
8407 ++it)
8408 {
8409 const ComObjPtr<MediumAttachment> &pAtt = *it;
8410
8411 // should never happen, but deal with NULL pointers in the list.
8412 AssertStmt(!pAtt.isNull(), continue);
8413
8414 // getControllerName() needs caller+read lock
8415 AutoCaller autoAttCaller(pAtt);
8416 if (FAILED(autoAttCaller.rc()))
8417 {
8418 atts.clear();
8419 return autoAttCaller.rc();
8420 }
8421 AutoReadLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
8422
8423 if (pAtt->getControllerName() == aName)
8424 atts.push_back(pAtt);
8425 }
8426
8427 return S_OK;
8428}
8429
8430/**
8431 * Helper for #saveSettings. Cares about renaming the settings directory and
8432 * file if the machine name was changed and about creating a new settings file
8433 * if this is a new machine.
8434 *
8435 * @note Must be never called directly but only from #saveSettings().
8436 */
8437HRESULT Machine::prepareSaveSettings(bool *pfNeedsGlobalSaveSettings)
8438{
8439 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8440
8441 HRESULT rc = S_OK;
8442
8443 bool fSettingsFileIsNew = !mData->pMachineConfigFile->fileExists();
8444
8445 /* attempt to rename the settings file if machine name is changed */
8446 if ( mUserData->s.fNameSync
8447 && mUserData.isBackedUp()
8448 && mUserData.backedUpData()->s.strName != mUserData->s.strName
8449 )
8450 {
8451 bool dirRenamed = false;
8452 bool fileRenamed = false;
8453
8454 Utf8Str configFile, newConfigFile;
8455 Utf8Str configFilePrev, newConfigFilePrev;
8456 Utf8Str configDir, newConfigDir;
8457
8458 do
8459 {
8460 int vrc = VINF_SUCCESS;
8461
8462 Utf8Str name = mUserData.backedUpData()->s.strName;
8463 Utf8Str newName = mUserData->s.strName;
8464
8465 configFile = mData->m_strConfigFileFull;
8466
8467 /* first, rename the directory if it matches the machine name */
8468 configDir = configFile;
8469 configDir.stripFilename();
8470 newConfigDir = configDir;
8471 if (!strcmp(RTPathFilename(configDir.c_str()), name.c_str()))
8472 {
8473 newConfigDir.stripFilename();
8474 newConfigDir.append(RTPATH_DELIMITER);
8475 newConfigDir.append(newName);
8476 /* new dir and old dir cannot be equal here because of 'if'
8477 * above and because name != newName */
8478 Assert(configDir != newConfigDir);
8479 if (!fSettingsFileIsNew)
8480 {
8481 /* perform real rename only if the machine is not new */
8482 vrc = RTPathRename(configDir.c_str(), newConfigDir.c_str(), 0);
8483 if (RT_FAILURE(vrc))
8484 {
8485 rc = setError(E_FAIL,
8486 tr("Could not rename the directory '%s' to '%s' to save the settings file (%Rrc)"),
8487 configDir.c_str(),
8488 newConfigDir.c_str(),
8489 vrc);
8490 break;
8491 }
8492 dirRenamed = true;
8493 }
8494 }
8495
8496 newConfigFile = Utf8StrFmt("%s%c%s.vbox",
8497 newConfigDir.c_str(), RTPATH_DELIMITER, newName.c_str());
8498
8499 /* then try to rename the settings file itself */
8500 if (newConfigFile != configFile)
8501 {
8502 /* get the path to old settings file in renamed directory */
8503 configFile = Utf8StrFmt("%s%c%s",
8504 newConfigDir.c_str(),
8505 RTPATH_DELIMITER,
8506 RTPathFilename(configFile.c_str()));
8507 if (!fSettingsFileIsNew)
8508 {
8509 /* perform real rename only if the machine is not new */
8510 vrc = RTFileRename(configFile.c_str(), newConfigFile.c_str(), 0);
8511 if (RT_FAILURE(vrc))
8512 {
8513 rc = setError(E_FAIL,
8514 tr("Could not rename the settings file '%s' to '%s' (%Rrc)"),
8515 configFile.c_str(),
8516 newConfigFile.c_str(),
8517 vrc);
8518 break;
8519 }
8520 fileRenamed = true;
8521 configFilePrev = configFile;
8522 configFilePrev += "-prev";
8523 newConfigFilePrev = newConfigFile;
8524 newConfigFilePrev += "-prev";
8525 RTFileRename(configFilePrev.c_str(), newConfigFilePrev.c_str(), 0);
8526 }
8527 }
8528
8529 // update m_strConfigFileFull amd mConfigFile
8530 mData->m_strConfigFileFull = newConfigFile;
8531 // compute the relative path too
8532 mParent->copyPathRelativeToConfig(newConfigFile, mData->m_strConfigFile);
8533
8534 // store the old and new so that VirtualBox::saveSettings() can update
8535 // the media registry
8536 if ( mData->mRegistered
8537 && configDir != newConfigDir)
8538 {
8539 mParent->rememberMachineNameChangeForMedia(configDir, newConfigDir);
8540
8541 if (pfNeedsGlobalSaveSettings)
8542 *pfNeedsGlobalSaveSettings = true;
8543 }
8544
8545 // in the saved state file path, replace the old directory with the new directory
8546 if (RTPathStartsWith(mSSData->strStateFilePath.c_str(), configDir.c_str()))
8547 mSSData->strStateFilePath = newConfigDir.append(mSSData->strStateFilePath.c_str() + configDir.length());
8548
8549 // and do the same thing for the saved state file paths of all the online snapshots
8550 if (mData->mFirstSnapshot)
8551 mData->mFirstSnapshot->updateSavedStatePaths(configDir.c_str(),
8552 newConfigDir.c_str());
8553 }
8554 while (0);
8555
8556 if (FAILED(rc))
8557 {
8558 /* silently try to rename everything back */
8559 if (fileRenamed)
8560 {
8561 RTFileRename(newConfigFilePrev.c_str(), configFilePrev.c_str(), 0);
8562 RTFileRename(newConfigFile.c_str(), configFile.c_str(), 0);
8563 }
8564 if (dirRenamed)
8565 RTPathRename(newConfigDir.c_str(), configDir.c_str(), 0);
8566 }
8567
8568 if (FAILED(rc)) return rc;
8569 }
8570
8571 if (fSettingsFileIsNew)
8572 {
8573 /* create a virgin config file */
8574 int vrc = VINF_SUCCESS;
8575
8576 /* ensure the settings directory exists */
8577 Utf8Str path(mData->m_strConfigFileFull);
8578 path.stripFilename();
8579 if (!RTDirExists(path.c_str()))
8580 {
8581 vrc = RTDirCreateFullPath(path.c_str(), 0777);
8582 if (RT_FAILURE(vrc))
8583 {
8584 return setError(E_FAIL,
8585 tr("Could not create a directory '%s' to save the settings file (%Rrc)"),
8586 path.c_str(),
8587 vrc);
8588 }
8589 }
8590
8591 /* Note: open flags must correlate with RTFileOpen() in lockConfig() */
8592 path = Utf8Str(mData->m_strConfigFileFull);
8593 RTFILE f = NIL_RTFILE;
8594 vrc = RTFileOpen(&f, path.c_str(),
8595 RTFILE_O_READWRITE | RTFILE_O_CREATE | RTFILE_O_DENY_WRITE);
8596 if (RT_FAILURE(vrc))
8597 return setError(E_FAIL,
8598 tr("Could not create the settings file '%s' (%Rrc)"),
8599 path.c_str(),
8600 vrc);
8601 RTFileClose(f);
8602 }
8603
8604 return rc;
8605}
8606
8607/**
8608 * Saves and commits machine data, user data and hardware data.
8609 *
8610 * Note that on failure, the data remains uncommitted.
8611 *
8612 * @a aFlags may combine the following flags:
8613 *
8614 * - SaveS_ResetCurStateModified: Resets mData->mCurrentStateModified to FALSE.
8615 * Used when saving settings after an operation that makes them 100%
8616 * correspond to the settings from the current snapshot.
8617 * - SaveS_InformCallbacksAnyway: Callbacks will be informed even if
8618 * #isReallyModified() returns false. This is necessary for cases when we
8619 * change machine data directly, not through the backup()/commit() mechanism.
8620 * - SaveS_Force: settings will be saved without doing a deep compare of the
8621 * settings structures. This is used when this is called because snapshots
8622 * have changed to avoid the overhead of the deep compare.
8623 *
8624 * @note Must be called from under this object's write lock. Locks children for
8625 * writing.
8626 *
8627 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been
8628 * initialized to false and that will be set to true by this function if
8629 * the caller must invoke VirtualBox::saveSettings() because the global
8630 * settings have changed. This will happen if a machine rename has been
8631 * saved and the global machine and media registries will therefore need
8632 * updating.
8633 */
8634HRESULT Machine::saveSettings(bool *pfNeedsGlobalSaveSettings,
8635 int aFlags /*= 0*/)
8636{
8637 LogFlowThisFuncEnter();
8638
8639 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8640
8641 /* make sure child objects are unable to modify the settings while we are
8642 * saving them */
8643 ensureNoStateDependencies();
8644
8645 AssertReturn(!isSnapshotMachine(),
8646 E_FAIL);
8647
8648 HRESULT rc = S_OK;
8649 bool fNeedsWrite = false;
8650
8651 /* First, prepare to save settings. It will care about renaming the
8652 * settings directory and file if the machine name was changed and about
8653 * creating a new settings file if this is a new machine. */
8654 rc = prepareSaveSettings(pfNeedsGlobalSaveSettings);
8655 if (FAILED(rc)) return rc;
8656
8657 // keep a pointer to the current settings structures
8658 settings::MachineConfigFile *pOldConfig = mData->pMachineConfigFile;
8659 settings::MachineConfigFile *pNewConfig = NULL;
8660
8661 try
8662 {
8663 // make a fresh one to have everyone write stuff into
8664 pNewConfig = new settings::MachineConfigFile(NULL);
8665 pNewConfig->copyBaseFrom(*mData->pMachineConfigFile);
8666
8667 // now go and copy all the settings data from COM to the settings structures
8668 // (this calles saveSettings() on all the COM objects in the machine)
8669 copyMachineDataToSettings(*pNewConfig);
8670
8671 if (aFlags & SaveS_ResetCurStateModified)
8672 {
8673 // this gets set by takeSnapshot() (if offline snapshot) and restoreSnapshot()
8674 mData->mCurrentStateModified = FALSE;
8675 fNeedsWrite = true; // always, no need to compare
8676 }
8677 else if (aFlags & SaveS_Force)
8678 {
8679 fNeedsWrite = true; // always, no need to compare
8680 }
8681 else
8682 {
8683 if (!mData->mCurrentStateModified)
8684 {
8685 // do a deep compare of the settings that we just saved with the settings
8686 // previously stored in the config file; this invokes MachineConfigFile::operator==
8687 // which does a deep compare of all the settings, which is expensive but less expensive
8688 // than writing out XML in vain
8689 bool fAnySettingsChanged = !(*pNewConfig == *pOldConfig);
8690
8691 // could still be modified if any settings changed
8692 mData->mCurrentStateModified = fAnySettingsChanged;
8693
8694 fNeedsWrite = fAnySettingsChanged;
8695 }
8696 else
8697 fNeedsWrite = true;
8698 }
8699
8700 pNewConfig->fCurrentStateModified = !!mData->mCurrentStateModified;
8701
8702 if (fNeedsWrite)
8703 // now spit it all out!
8704 pNewConfig->write(mData->m_strConfigFileFull);
8705
8706 mData->pMachineConfigFile = pNewConfig;
8707 delete pOldConfig;
8708 commit();
8709
8710 // after saving settings, we are no longer different from the XML on disk
8711 mData->flModifications = 0;
8712 }
8713 catch (HRESULT err)
8714 {
8715 // we assume that error info is set by the thrower
8716 rc = err;
8717
8718 // restore old config
8719 delete pNewConfig;
8720 mData->pMachineConfigFile = pOldConfig;
8721 }
8722 catch (...)
8723 {
8724 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8725 }
8726
8727 if (fNeedsWrite || (aFlags & SaveS_InformCallbacksAnyway))
8728 {
8729 /* Fire the data change event, even on failure (since we've already
8730 * committed all data). This is done only for SessionMachines because
8731 * mutable Machine instances are always not registered (i.e. private
8732 * to the client process that creates them) and thus don't need to
8733 * inform callbacks. */
8734 if (isSessionMachine())
8735 mParent->onMachineDataChange(mData->mUuid);
8736 }
8737
8738 LogFlowThisFunc(("rc=%08X\n", rc));
8739 LogFlowThisFuncLeave();
8740 return rc;
8741}
8742
8743/**
8744 * Implementation for saving the machine settings into the given
8745 * settings::MachineConfigFile instance. This copies machine extradata
8746 * from the previous machine config file in the instance data, if any.
8747 *
8748 * This gets called from two locations:
8749 *
8750 * -- Machine::saveSettings(), during the regular XML writing;
8751 *
8752 * -- Appliance::buildXMLForOneVirtualSystem(), when a machine gets
8753 * exported to OVF and we write the VirtualBox proprietary XML
8754 * into a <vbox:Machine> tag.
8755 *
8756 * This routine fills all the fields in there, including snapshots, *except*
8757 * for the following:
8758 *
8759 * -- fCurrentStateModified. There is some special logic associated with that.
8760 *
8761 * The caller can then call MachineConfigFile::write() or do something else
8762 * with it.
8763 *
8764 * Caller must hold the machine lock!
8765 *
8766 * This throws XML errors and HRESULT, so the caller must have a catch block!
8767 */
8768void Machine::copyMachineDataToSettings(settings::MachineConfigFile &config)
8769{
8770 // deep copy extradata
8771 config.mapExtraDataItems = mData->pMachineConfigFile->mapExtraDataItems;
8772
8773 config.uuid = mData->mUuid;
8774
8775 // copy name, description, OS type, teleport, UTC etc.
8776 config.machineUserData = mUserData->s;
8777
8778 if ( mData->mMachineState == MachineState_Saved
8779 || mData->mMachineState == MachineState_Restoring
8780 // when deleting a snapshot we may or may not have a saved state in the current state,
8781 // so let's not assert here please
8782 || ( ( mData->mMachineState == MachineState_DeletingSnapshot
8783 || mData->mMachineState == MachineState_DeletingSnapshotOnline
8784 || mData->mMachineState == MachineState_DeletingSnapshotPaused)
8785 && (!mSSData->strStateFilePath.isEmpty())
8786 )
8787 )
8788 {
8789 Assert(!mSSData->strStateFilePath.isEmpty());
8790 /* try to make the file name relative to the settings file dir */
8791 copyPathRelativeToMachine(mSSData->strStateFilePath, config.strStateFile);
8792 }
8793 else
8794 {
8795 Assert(mSSData->strStateFilePath.isEmpty() || mData->mMachineState == MachineState_Saving);
8796 config.strStateFile.setNull();
8797 }
8798
8799 if (mData->mCurrentSnapshot)
8800 config.uuidCurrentSnapshot = mData->mCurrentSnapshot->getId();
8801 else
8802 config.uuidCurrentSnapshot.clear();
8803
8804 config.timeLastStateChange = mData->mLastStateChange;
8805 config.fAborted = (mData->mMachineState == MachineState_Aborted);
8806 /// @todo Live Migration: config.fTeleported = (mData->mMachineState == MachineState_Teleported);
8807
8808 HRESULT rc = saveHardware(config.hardwareMachine);
8809 if (FAILED(rc)) throw rc;
8810
8811 rc = saveStorageControllers(config.storageMachine);
8812 if (FAILED(rc)) throw rc;
8813
8814 // save machine's media registry if this is VirtualBox 4.0 or later
8815 if (config.canHaveOwnMediaRegistry())
8816 {
8817 // determine machine folder
8818 Utf8Str strMachineFolder = getSettingsFileFull();
8819 strMachineFolder.stripFilename();
8820 mParent->saveMediaRegistry(config.mediaRegistry,
8821 getId(), // only media with registry ID == machine UUID
8822 strMachineFolder);
8823 // this throws HRESULT
8824 }
8825
8826 // save snapshots
8827 rc = saveAllSnapshots(config);
8828 if (FAILED(rc)) throw rc;
8829}
8830
8831/**
8832 * Saves all snapshots of the machine into the given machine config file. Called
8833 * from Machine::buildMachineXML() and SessionMachine::deleteSnapshotHandler().
8834 * @param config
8835 * @return
8836 */
8837HRESULT Machine::saveAllSnapshots(settings::MachineConfigFile &config)
8838{
8839 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8840
8841 HRESULT rc = S_OK;
8842
8843 try
8844 {
8845 config.llFirstSnapshot.clear();
8846
8847 if (mData->mFirstSnapshot)
8848 {
8849 settings::Snapshot snapNew;
8850 config.llFirstSnapshot.push_back(snapNew);
8851
8852 // get reference to the fresh copy of the snapshot on the list and
8853 // work on that copy directly to avoid excessive copying later
8854 settings::Snapshot &snap = config.llFirstSnapshot.front();
8855
8856 rc = mData->mFirstSnapshot->saveSnapshot(snap, false /*aAttrsOnly*/);
8857 if (FAILED(rc)) throw rc;
8858 }
8859
8860// if (mType == IsSessionMachine)
8861// mParent->onMachineDataChange(mData->mUuid); @todo is this necessary?
8862
8863 }
8864 catch (HRESULT err)
8865 {
8866 /* we assume that error info is set by the thrower */
8867 rc = err;
8868 }
8869 catch (...)
8870 {
8871 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
8872 }
8873
8874 return rc;
8875}
8876
8877/**
8878 * Saves the VM hardware configuration. It is assumed that the
8879 * given node is empty.
8880 *
8881 * @param aNode <Hardware> node to save the VM hardware configuration to.
8882 */
8883HRESULT Machine::saveHardware(settings::Hardware &data)
8884{
8885 HRESULT rc = S_OK;
8886
8887 try
8888 {
8889 /* The hardware version attribute (optional).
8890 Automatically upgrade from 1 to 2 when there is no saved state. (ugly!) */
8891 if ( mHWData->mHWVersion == "1"
8892 && mSSData->strStateFilePath.isEmpty()
8893 )
8894 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. */
8895
8896 data.strVersion = mHWData->mHWVersion;
8897 data.uuid = mHWData->mHardwareUUID;
8898
8899 // CPU
8900 data.fHardwareVirt = !!mHWData->mHWVirtExEnabled;
8901 data.fHardwareVirtExclusive = !!mHWData->mHWVirtExExclusive;
8902 data.fNestedPaging = !!mHWData->mHWVirtExNestedPagingEnabled;
8903 data.fLargePages = !!mHWData->mHWVirtExLargePagesEnabled;
8904 data.fVPID = !!mHWData->mHWVirtExVPIDEnabled;
8905 data.fHardwareVirtForce = !!mHWData->mHWVirtExForceEnabled;
8906 data.fPAE = !!mHWData->mPAEEnabled;
8907 data.fSyntheticCpu = !!mHWData->mSyntheticCpu;
8908
8909 /* Standard and Extended CPUID leafs. */
8910 data.llCpuIdLeafs.clear();
8911 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdStdLeafs); idx++)
8912 {
8913 if (mHWData->mCpuIdStdLeafs[idx].ulId != UINT32_MAX)
8914 data.llCpuIdLeafs.push_back(mHWData->mCpuIdStdLeafs[idx]);
8915 }
8916 for (unsigned idx = 0; idx < RT_ELEMENTS(mHWData->mCpuIdExtLeafs); idx++)
8917 {
8918 if (mHWData->mCpuIdExtLeafs[idx].ulId != UINT32_MAX)
8919 data.llCpuIdLeafs.push_back(mHWData->mCpuIdExtLeafs[idx]);
8920 }
8921
8922 data.cCPUs = mHWData->mCPUCount;
8923 data.fCpuHotPlug = !!mHWData->mCPUHotPlugEnabled;
8924 data.ulCpuExecutionCap = mHWData->mCpuExecutionCap;
8925
8926 data.llCpus.clear();
8927 if (data.fCpuHotPlug)
8928 {
8929 for (unsigned idx = 0; idx < data.cCPUs; idx++)
8930 {
8931 if (mHWData->mCPUAttached[idx])
8932 {
8933 settings::Cpu cpu;
8934 cpu.ulId = idx;
8935 data.llCpus.push_back(cpu);
8936 }
8937 }
8938 }
8939
8940 // memory
8941 data.ulMemorySizeMB = mHWData->mMemorySize;
8942 data.fPageFusionEnabled = !!mHWData->mPageFusionEnabled;
8943
8944 // firmware
8945 data.firmwareType = mHWData->mFirmwareType;
8946
8947 // HID
8948 data.pointingHidType = mHWData->mPointingHidType;
8949 data.keyboardHidType = mHWData->mKeyboardHidType;
8950
8951 // chipset
8952 data.chipsetType = mHWData->mChipsetType;
8953
8954 // HPET
8955 data.fHpetEnabled = !!mHWData->mHpetEnabled;
8956
8957 // boot order
8958 data.mapBootOrder.clear();
8959 for (size_t i = 0;
8960 i < RT_ELEMENTS(mHWData->mBootOrder);
8961 ++i)
8962 data.mapBootOrder[i] = mHWData->mBootOrder[i];
8963
8964 // display
8965 data.ulVRAMSizeMB = mHWData->mVRAMSize;
8966 data.cMonitors = mHWData->mMonitorCount;
8967 data.fAccelerate3D = !!mHWData->mAccelerate3DEnabled;
8968 data.fAccelerate2DVideo = !!mHWData->mAccelerate2DVideoEnabled;
8969
8970 /* VRDEServer settings (optional) */
8971 rc = mVRDEServer->saveSettings(data.vrdeSettings);
8972 if (FAILED(rc)) throw rc;
8973
8974 /* BIOS (required) */
8975 rc = mBIOSSettings->saveSettings(data.biosSettings);
8976 if (FAILED(rc)) throw rc;
8977
8978 /* USB Controller (required) */
8979 rc = mUSBController->saveSettings(data.usbController);
8980 if (FAILED(rc)) throw rc;
8981
8982 /* Network adapters (required) */
8983 data.llNetworkAdapters.clear();
8984 for (ULONG slot = 0;
8985 slot < RT_ELEMENTS(mNetworkAdapters);
8986 ++slot)
8987 {
8988 settings::NetworkAdapter nic;
8989 nic.ulSlot = slot;
8990 rc = mNetworkAdapters[slot]->saveSettings(nic);
8991 if (FAILED(rc)) throw rc;
8992
8993 data.llNetworkAdapters.push_back(nic);
8994 }
8995
8996 /* Serial ports */
8997 data.llSerialPorts.clear();
8998 for (ULONG slot = 0;
8999 slot < RT_ELEMENTS(mSerialPorts);
9000 ++slot)
9001 {
9002 settings::SerialPort s;
9003 s.ulSlot = slot;
9004 rc = mSerialPorts[slot]->saveSettings(s);
9005 if (FAILED(rc)) return rc;
9006
9007 data.llSerialPorts.push_back(s);
9008 }
9009
9010 /* Parallel ports */
9011 data.llParallelPorts.clear();
9012 for (ULONG slot = 0;
9013 slot < RT_ELEMENTS(mParallelPorts);
9014 ++slot)
9015 {
9016 settings::ParallelPort p;
9017 p.ulSlot = slot;
9018 rc = mParallelPorts[slot]->saveSettings(p);
9019 if (FAILED(rc)) return rc;
9020
9021 data.llParallelPorts.push_back(p);
9022 }
9023
9024 /* Audio adapter */
9025 rc = mAudioAdapter->saveSettings(data.audioAdapter);
9026 if (FAILED(rc)) return rc;
9027
9028 /* Shared folders */
9029 data.llSharedFolders.clear();
9030 for (HWData::SharedFolderList::const_iterator it = mHWData->mSharedFolders.begin();
9031 it != mHWData->mSharedFolders.end();
9032 ++it)
9033 {
9034 SharedFolder *pSF = *it;
9035 AutoCaller sfCaller(pSF);
9036 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
9037 settings::SharedFolder sf;
9038 sf.strName = pSF->getName();
9039 sf.strHostPath = pSF->getHostPath();
9040 sf.fWritable = !!pSF->isWritable();
9041 sf.fAutoMount = !!pSF->isAutoMounted();
9042
9043 data.llSharedFolders.push_back(sf);
9044 }
9045
9046 // clipboard
9047 data.clipboardMode = mHWData->mClipboardMode;
9048
9049 /* Guest */
9050 data.ulMemoryBalloonSize = mHWData->mMemoryBalloonSize;
9051
9052 // IO settings
9053 data.ioSettings.fIoCacheEnabled = !!mHWData->mIoCacheEnabled;
9054 data.ioSettings.ulIoCacheSize = mHWData->mIoCacheSize;
9055
9056 /* BandwidthControl (required) */
9057 rc = mBandwidthControl->saveSettings(data.ioSettings);
9058 if (FAILED(rc)) throw rc;
9059
9060 /* Host PCI devices */
9061 for (HWData::PciDeviceAssignmentList::const_iterator it = mHWData->mPciDeviceAssignments.begin();
9062 it != mHWData->mPciDeviceAssignments.end();
9063 ++it)
9064 {
9065 ComObjPtr<PciDeviceAttachment> pda = *it;
9066 settings::HostPciDeviceAttachment hpda;
9067
9068 rc = pda->saveSettings(hpda);
9069 if (FAILED(rc)) throw rc;
9070
9071 data.pciAttachments.push_back(hpda);
9072 }
9073
9074
9075 // guest properties
9076 data.llGuestProperties.clear();
9077#ifdef VBOX_WITH_GUEST_PROPS
9078 for (HWData::GuestPropertyList::const_iterator it = mHWData->mGuestProperties.begin();
9079 it != mHWData->mGuestProperties.end();
9080 ++it)
9081 {
9082 HWData::GuestProperty property = *it;
9083
9084 /* Remove transient guest properties at shutdown unless we
9085 * are saving state */
9086 if ( ( mData->mMachineState == MachineState_PoweredOff
9087 || mData->mMachineState == MachineState_Aborted
9088 || mData->mMachineState == MachineState_Teleported)
9089 && ( property.mFlags & guestProp::TRANSIENT
9090 || property.mFlags & guestProp::TRANSRESET))
9091 continue;
9092 settings::GuestProperty prop;
9093 prop.strName = property.strName;
9094 prop.strValue = property.strValue;
9095 prop.timestamp = property.mTimestamp;
9096 char szFlags[guestProp::MAX_FLAGS_LEN + 1];
9097 guestProp::writeFlags(property.mFlags, szFlags);
9098 prop.strFlags = szFlags;
9099
9100 data.llGuestProperties.push_back(prop);
9101 }
9102
9103 data.strNotificationPatterns = mHWData->mGuestPropertyNotificationPatterns;
9104 /* I presume this doesn't require a backup(). */
9105 mData->mGuestPropertiesModified = FALSE;
9106#endif /* VBOX_WITH_GUEST_PROPS defined */
9107 }
9108 catch(std::bad_alloc &)
9109 {
9110 return E_OUTOFMEMORY;
9111 }
9112
9113 AssertComRC(rc);
9114 return rc;
9115}
9116
9117/**
9118 * Saves the storage controller configuration.
9119 *
9120 * @param aNode <StorageControllers> node to save the VM hardware configuration to.
9121 */
9122HRESULT Machine::saveStorageControllers(settings::Storage &data)
9123{
9124 data.llStorageControllers.clear();
9125
9126 for (StorageControllerList::const_iterator it = mStorageControllers->begin();
9127 it != mStorageControllers->end();
9128 ++it)
9129 {
9130 HRESULT rc;
9131 ComObjPtr<StorageController> pCtl = *it;
9132
9133 settings::StorageController ctl;
9134 ctl.strName = pCtl->getName();
9135 ctl.controllerType = pCtl->getControllerType();
9136 ctl.storageBus = pCtl->getStorageBus();
9137 ctl.ulInstance = pCtl->getInstance();
9138 ctl.fBootable = pCtl->getBootable();
9139
9140 /* Save the port count. */
9141 ULONG portCount;
9142 rc = pCtl->COMGETTER(PortCount)(&portCount);
9143 ComAssertComRCRet(rc, rc);
9144 ctl.ulPortCount = portCount;
9145
9146 /* Save fUseHostIOCache */
9147 BOOL fUseHostIOCache;
9148 rc = pCtl->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9149 ComAssertComRCRet(rc, rc);
9150 ctl.fUseHostIOCache = !!fUseHostIOCache;
9151
9152 /* Save IDE emulation settings. */
9153 if (ctl.controllerType == StorageControllerType_IntelAhci)
9154 {
9155 if ( (FAILED(rc = pCtl->GetIDEEmulationPort(0, (LONG*)&ctl.lIDE0MasterEmulationPort)))
9156 || (FAILED(rc = pCtl->GetIDEEmulationPort(1, (LONG*)&ctl.lIDE0SlaveEmulationPort)))
9157 || (FAILED(rc = pCtl->GetIDEEmulationPort(2, (LONG*)&ctl.lIDE1MasterEmulationPort)))
9158 || (FAILED(rc = pCtl->GetIDEEmulationPort(3, (LONG*)&ctl.lIDE1SlaveEmulationPort)))
9159 )
9160 ComAssertComRCRet(rc, rc);
9161 }
9162
9163 /* save the devices now. */
9164 rc = saveStorageDevices(pCtl, ctl);
9165 ComAssertComRCRet(rc, rc);
9166
9167 data.llStorageControllers.push_back(ctl);
9168 }
9169
9170 return S_OK;
9171}
9172
9173/**
9174 * Saves the hard disk configuration.
9175 */
9176HRESULT Machine::saveStorageDevices(ComObjPtr<StorageController> aStorageController,
9177 settings::StorageController &data)
9178{
9179 MediaData::AttachmentList atts;
9180
9181 HRESULT rc = getMediumAttachmentsOfController(Bstr(aStorageController->getName()).raw(), atts);
9182 if (FAILED(rc)) return rc;
9183
9184 data.llAttachedDevices.clear();
9185 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9186 it != atts.end();
9187 ++it)
9188 {
9189 settings::AttachedDevice dev;
9190
9191 MediumAttachment *pAttach = *it;
9192 Medium *pMedium = pAttach->getMedium();
9193
9194 dev.deviceType = pAttach->getType();
9195 dev.lPort = pAttach->getPort();
9196 dev.lDevice = pAttach->getDevice();
9197 if (pMedium)
9198 {
9199 if (pMedium->isHostDrive())
9200 dev.strHostDriveSrc = pMedium->getLocationFull();
9201 else
9202 dev.uuid = pMedium->getId();
9203 dev.fPassThrough = pAttach->getPassthrough();
9204 dev.fTempEject = pAttach->getTempEject();
9205 dev.fDiscard = pAttach->getDiscard();
9206 }
9207
9208 dev.strBwGroup = pAttach->getBandwidthGroup();
9209
9210 data.llAttachedDevices.push_back(dev);
9211 }
9212
9213 return S_OK;
9214}
9215
9216/**
9217 * Saves machine state settings as defined by aFlags
9218 * (SaveSTS_* values).
9219 *
9220 * @param aFlags Combination of SaveSTS_* flags.
9221 *
9222 * @note Locks objects for writing.
9223 */
9224HRESULT Machine::saveStateSettings(int aFlags)
9225{
9226 if (aFlags == 0)
9227 return S_OK;
9228
9229 AutoCaller autoCaller(this);
9230 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9231
9232 /* This object's write lock is also necessary to serialize file access
9233 * (prevent concurrent reads and writes) */
9234 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9235
9236 HRESULT rc = S_OK;
9237
9238 Assert(mData->pMachineConfigFile);
9239
9240 try
9241 {
9242 if (aFlags & SaveSTS_CurStateModified)
9243 mData->pMachineConfigFile->fCurrentStateModified = true;
9244
9245 if (aFlags & SaveSTS_StateFilePath)
9246 {
9247 if (!mSSData->strStateFilePath.isEmpty())
9248 /* try to make the file name relative to the settings file dir */
9249 copyPathRelativeToMachine(mSSData->strStateFilePath, mData->pMachineConfigFile->strStateFile);
9250 else
9251 mData->pMachineConfigFile->strStateFile.setNull();
9252 }
9253
9254 if (aFlags & SaveSTS_StateTimeStamp)
9255 {
9256 Assert( mData->mMachineState != MachineState_Aborted
9257 || mSSData->strStateFilePath.isEmpty());
9258
9259 mData->pMachineConfigFile->timeLastStateChange = mData->mLastStateChange;
9260
9261 mData->pMachineConfigFile->fAborted = (mData->mMachineState == MachineState_Aborted);
9262//@todo live migration mData->pMachineConfigFile->fTeleported = (mData->mMachineState == MachineState_Teleported);
9263 }
9264
9265 mData->pMachineConfigFile->write(mData->m_strConfigFileFull);
9266 }
9267 catch (...)
9268 {
9269 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
9270 }
9271
9272 return rc;
9273}
9274
9275/**
9276 * Ensures that the given medium is added to a media registry. If this machine
9277 * was created with 4.0 or later, then the machine registry is used. Otherwise
9278 * the global VirtualBox media registry is used. If the medium was actually
9279 * added to a registry (because it wasn't in the registry yet), the UUID of
9280 * that registry is added to the given list so that the caller can save the
9281 * registry.
9282 *
9283 * Caller must hold machine read lock and at least media tree read lock!
9284 * Caller must NOT hold any medium locks.
9285 *
9286 * @param pMedium
9287 * @param llRegistriesThatNeedSaving
9288 * @param puuid Optional buffer that receives the registry UUID that was used.
9289 */
9290void Machine::addMediumToRegistry(ComObjPtr<Medium> &pMedium,
9291 GuidList &llRegistriesThatNeedSaving,
9292 Guid *puuid)
9293{
9294 ComObjPtr<Medium> pBase = pMedium->getBase();
9295 /* Paranoia checks: do not hold medium locks. */
9296 AssertReturnVoid(!pMedium->isWriteLockOnCurrentThread());
9297 AssertReturnVoid(!pBase->isWriteLockOnCurrentThread());
9298
9299 // decide which medium registry to use now that the medium is attached:
9300 Guid uuid;
9301 if (mData->pMachineConfigFile->canHaveOwnMediaRegistry())
9302 // machine XML is VirtualBox 4.0 or higher:
9303 uuid = getId(); // machine UUID
9304 else
9305 uuid = mParent->getGlobalRegistryId(); // VirtualBox global registry UUID
9306
9307 bool fAdd = false;
9308 if (pMedium->addRegistry(uuid, false /* fRecurse */))
9309 {
9310 // registry actually changed:
9311 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9312 fAdd = true;
9313 }
9314
9315 /* For more complex hard disk structures it can happen that the base
9316 * medium isn't yet associated with any medium registry. Do that now. */
9317 if (pMedium != pBase)
9318 {
9319 if ( pBase->addRegistry(uuid, true /* fRecurse */)
9320 && !fAdd)
9321 {
9322 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
9323 fAdd = true;
9324 }
9325 }
9326
9327 if (puuid)
9328 *puuid = uuid;
9329}
9330
9331/**
9332 * Creates differencing hard disks for all normal hard disks attached to this
9333 * machine and a new set of attachments to refer to created disks.
9334 *
9335 * Used when taking a snapshot or when deleting the current state. Gets called
9336 * from SessionMachine::BeginTakingSnapshot() and SessionMachine::restoreSnapshotHandler().
9337 *
9338 * This method assumes that mMediaData contains the original hard disk attachments
9339 * it needs to create diffs for. On success, these attachments will be replaced
9340 * with the created diffs. On failure, #deleteImplicitDiffs() is implicitly
9341 * called to delete created diffs which will also rollback mMediaData and restore
9342 * whatever was backed up before calling this method.
9343 *
9344 * Attachments with non-normal hard disks are left as is.
9345 *
9346 * If @a aOnline is @c false then the original hard disks that require implicit
9347 * diffs will be locked for reading. Otherwise it is assumed that they are
9348 * already locked for writing (when the VM was started). Note that in the latter
9349 * case it is responsibility of the caller to lock the newly created diffs for
9350 * writing if this method succeeds.
9351 *
9352 * @param aProgress Progress object to run (must contain at least as
9353 * many operations left as the number of hard disks
9354 * attached).
9355 * @param aOnline Whether the VM was online prior to this operation.
9356 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9357 *
9358 * @note The progress object is not marked as completed, neither on success nor
9359 * on failure. This is a responsibility of the caller.
9360 *
9361 * @note Locks this object for writing.
9362 */
9363HRESULT Machine::createImplicitDiffs(IProgress *aProgress,
9364 ULONG aWeight,
9365 bool aOnline,
9366 GuidList *pllRegistriesThatNeedSaving)
9367{
9368 LogFlowThisFunc(("aOnline=%d\n", aOnline));
9369
9370 AutoCaller autoCaller(this);
9371 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9372
9373 AutoMultiWriteLock2 alock(this->lockHandle(),
9374 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
9375
9376 /* must be in a protective state because we leave the lock below */
9377 AssertReturn( mData->mMachineState == MachineState_Saving
9378 || mData->mMachineState == MachineState_LiveSnapshotting
9379 || mData->mMachineState == MachineState_RestoringSnapshot
9380 || mData->mMachineState == MachineState_DeletingSnapshot
9381 , E_FAIL);
9382
9383 HRESULT rc = S_OK;
9384
9385 MediumLockListMap lockedMediaOffline;
9386 MediumLockListMap *lockedMediaMap;
9387 if (aOnline)
9388 lockedMediaMap = &mData->mSession.mLockedMedia;
9389 else
9390 lockedMediaMap = &lockedMediaOffline;
9391
9392 try
9393 {
9394 if (!aOnline)
9395 {
9396 /* lock all attached hard disks early to detect "in use"
9397 * situations before creating actual diffs */
9398 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9399 it != mMediaData->mAttachments.end();
9400 ++it)
9401 {
9402 MediumAttachment* pAtt = *it;
9403 if (pAtt->getType() == DeviceType_HardDisk)
9404 {
9405 Medium* pMedium = pAtt->getMedium();
9406 Assert(pMedium);
9407
9408 MediumLockList *pMediumLockList(new MediumLockList());
9409 rc = pMedium->createMediumLockList(true /* fFailIfInaccessible */,
9410 false /* fMediumLockWrite */,
9411 NULL,
9412 *pMediumLockList);
9413 if (FAILED(rc))
9414 {
9415 delete pMediumLockList;
9416 throw rc;
9417 }
9418 rc = lockedMediaMap->Insert(pAtt, pMediumLockList);
9419 if (FAILED(rc))
9420 {
9421 throw setError(rc,
9422 tr("Collecting locking information for all attached media failed"));
9423 }
9424 }
9425 }
9426
9427 /* Now lock all media. If this fails, nothing is locked. */
9428 rc = lockedMediaMap->Lock();
9429 if (FAILED(rc))
9430 {
9431 throw setError(rc,
9432 tr("Locking of attached media failed"));
9433 }
9434 }
9435
9436 /* remember the current list (note that we don't use backup() since
9437 * mMediaData may be already backed up) */
9438 MediaData::AttachmentList atts = mMediaData->mAttachments;
9439
9440 /* start from scratch */
9441 mMediaData->mAttachments.clear();
9442
9443 /* go through remembered attachments and create diffs for normal hard
9444 * disks and attach them */
9445 for (MediaData::AttachmentList::const_iterator it = atts.begin();
9446 it != atts.end();
9447 ++it)
9448 {
9449 MediumAttachment* pAtt = *it;
9450
9451 DeviceType_T devType = pAtt->getType();
9452 Medium* pMedium = pAtt->getMedium();
9453
9454 if ( devType != DeviceType_HardDisk
9455 || pMedium == NULL
9456 || pMedium->getType() != MediumType_Normal)
9457 {
9458 /* copy the attachment as is */
9459
9460 /** @todo the progress object created in Console::TakeSnaphot
9461 * only expects operations for hard disks. Later other
9462 * device types need to show up in the progress as well. */
9463 if (devType == DeviceType_HardDisk)
9464 {
9465 if (pMedium == NULL)
9466 aProgress->SetNextOperation(Bstr(tr("Skipping attachment without medium")).raw(),
9467 aWeight); // weight
9468 else
9469 aProgress->SetNextOperation(BstrFmt(tr("Skipping medium '%s'"),
9470 pMedium->getBase()->getName().c_str()).raw(),
9471 aWeight); // weight
9472 }
9473
9474 mMediaData->mAttachments.push_back(pAtt);
9475 continue;
9476 }
9477
9478 /* need a diff */
9479 aProgress->SetNextOperation(BstrFmt(tr("Creating differencing hard disk for '%s'"),
9480 pMedium->getBase()->getName().c_str()).raw(),
9481 aWeight); // weight
9482
9483 Utf8Str strFullSnapshotFolder;
9484 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
9485
9486 ComObjPtr<Medium> diff;
9487 diff.createObject();
9488 // store the diff in the same registry as the parent
9489 // (this cannot fail here because we can't create implicit diffs for
9490 // unregistered images)
9491 Guid uuidRegistryParent;
9492 bool fInRegistry = pMedium->getFirstRegistryMachineId(uuidRegistryParent);
9493 Assert(fInRegistry); NOREF(fInRegistry);
9494 rc = diff->init(mParent,
9495 pMedium->getPreferredDiffFormat(),
9496 strFullSnapshotFolder.append(RTPATH_SLASH_STR),
9497 uuidRegistryParent,
9498 pllRegistriesThatNeedSaving);
9499 if (FAILED(rc)) throw rc;
9500
9501 /** @todo r=bird: How is the locking and diff image cleaned up if we fail before
9502 * the push_back? Looks like we're going to leave medium with the
9503 * wrong kind of lock (general issue with if we fail anywhere at all)
9504 * and an orphaned VDI in the snapshots folder. */
9505
9506 /* update the appropriate lock list */
9507 MediumLockList *pMediumLockList;
9508 rc = lockedMediaMap->Get(pAtt, pMediumLockList);
9509 AssertComRCThrowRC(rc);
9510 if (aOnline)
9511 {
9512 rc = pMediumLockList->Update(pMedium, false);
9513 AssertComRCThrowRC(rc);
9514 }
9515
9516 /* leave the locks before the potentially lengthy operation */
9517 alock.release();
9518 rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
9519 pMediumLockList,
9520 NULL /* aProgress */,
9521 true /* aWait */,
9522 pllRegistriesThatNeedSaving);
9523 alock.acquire();
9524 if (FAILED(rc)) throw rc;
9525
9526 rc = lockedMediaMap->Unlock();
9527 AssertComRCThrowRC(rc);
9528 rc = pMediumLockList->Append(diff, true);
9529 AssertComRCThrowRC(rc);
9530 rc = lockedMediaMap->Lock();
9531 AssertComRCThrowRC(rc);
9532
9533 rc = diff->addBackReference(mData->mUuid);
9534 AssertComRCThrowRC(rc);
9535
9536 /* add a new attachment */
9537 ComObjPtr<MediumAttachment> attachment;
9538 attachment.createObject();
9539 rc = attachment->init(this,
9540 diff,
9541 pAtt->getControllerName(),
9542 pAtt->getPort(),
9543 pAtt->getDevice(),
9544 DeviceType_HardDisk,
9545 true /* aImplicit */,
9546 false /* aPassthrough */,
9547 false /* aTempEject */,
9548 pAtt->getNonRotational(),
9549 pAtt->getDiscard(),
9550 pAtt->getBandwidthGroup());
9551 if (FAILED(rc)) throw rc;
9552
9553 rc = lockedMediaMap->ReplaceKey(pAtt, attachment);
9554 AssertComRCThrowRC(rc);
9555 mMediaData->mAttachments.push_back(attachment);
9556 }
9557 }
9558 catch (HRESULT aRC) { rc = aRC; }
9559
9560 /* unlock all hard disks we locked */
9561 if (!aOnline)
9562 {
9563 ErrorInfoKeeper eik;
9564
9565 HRESULT rc1 = lockedMediaMap->Clear();
9566 AssertComRC(rc1);
9567 }
9568
9569 if (FAILED(rc))
9570 {
9571 MultiResult mrc = rc;
9572
9573 mrc = deleteImplicitDiffs(pllRegistriesThatNeedSaving);
9574 }
9575
9576 return rc;
9577}
9578
9579/**
9580 * Deletes implicit differencing hard disks created either by
9581 * #createImplicitDiffs() or by #AttachDevice() and rolls back mMediaData.
9582 *
9583 * Note that to delete hard disks created by #AttachDevice() this method is
9584 * called from #fixupMedia() when the changes are rolled back.
9585 *
9586 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9587 *
9588 * @note Locks this object for writing.
9589 */
9590HRESULT Machine::deleteImplicitDiffs(GuidList *pllRegistriesThatNeedSaving)
9591{
9592 AutoCaller autoCaller(this);
9593 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
9594
9595 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9596 LogFlowThisFuncEnter();
9597
9598 AssertReturn(mMediaData.isBackedUp(), E_FAIL);
9599
9600 HRESULT rc = S_OK;
9601
9602 MediaData::AttachmentList implicitAtts;
9603
9604 const MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9605
9606 /* enumerate new attachments */
9607 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9608 it != mMediaData->mAttachments.end();
9609 ++it)
9610 {
9611 ComObjPtr<Medium> hd = (*it)->getMedium();
9612 if (hd.isNull())
9613 continue;
9614
9615 if ((*it)->isImplicit())
9616 {
9617 /* deassociate and mark for deletion */
9618 LogFlowThisFunc(("Detaching '%s', pending deletion\n", (*it)->getLogName()));
9619 rc = hd->removeBackReference(mData->mUuid);
9620 AssertComRC(rc);
9621 implicitAtts.push_back(*it);
9622 continue;
9623 }
9624
9625 /* was this hard disk attached before? */
9626 if (!findAttachment(oldAtts, hd))
9627 {
9628 /* no: de-associate */
9629 LogFlowThisFunc(("Detaching '%s', no deletion\n", (*it)->getLogName()));
9630 rc = hd->removeBackReference(mData->mUuid);
9631 AssertComRC(rc);
9632 continue;
9633 }
9634 LogFlowThisFunc(("Not detaching '%s'\n", (*it)->getLogName()));
9635 }
9636
9637 /* rollback hard disk changes */
9638 mMediaData.rollback();
9639
9640 MultiResult mrc(S_OK);
9641
9642 /* delete unused implicit diffs */
9643 if (implicitAtts.size() != 0)
9644 {
9645 /* will leave the lock before the potentially lengthy
9646 * operation, so protect with the special state (unless already
9647 * protected) */
9648 MachineState_T oldState = mData->mMachineState;
9649 if ( oldState != MachineState_Saving
9650 && oldState != MachineState_LiveSnapshotting
9651 && oldState != MachineState_RestoringSnapshot
9652 && oldState != MachineState_DeletingSnapshot
9653 && oldState != MachineState_DeletingSnapshotOnline
9654 && oldState != MachineState_DeletingSnapshotPaused
9655 )
9656 setMachineState(MachineState_SettingUp);
9657
9658 alock.leave();
9659
9660 for (MediaData::AttachmentList::const_iterator it = implicitAtts.begin();
9661 it != implicitAtts.end();
9662 ++it)
9663 {
9664 LogFlowThisFunc(("Deleting '%s'\n", (*it)->getLogName()));
9665 ComObjPtr<Medium> hd = (*it)->getMedium();
9666
9667 rc = hd->deleteStorage(NULL /*aProgress*/, true /*aWait*/,
9668 pllRegistriesThatNeedSaving);
9669 AssertMsg(SUCCEEDED(rc), ("rc=%Rhrc it=%s hd=%s\n", rc, (*it)->getLogName(), hd->getLocationFull().c_str() ));
9670 mrc = rc;
9671 }
9672
9673 alock.enter();
9674
9675 if (mData->mMachineState == MachineState_SettingUp)
9676 setMachineState(oldState);
9677 }
9678
9679 return mrc;
9680}
9681
9682/**
9683 * Looks through the given list of media attachments for one with the given parameters
9684 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9685 * can be searched as well if needed.
9686 *
9687 * @param list
9688 * @param aControllerName
9689 * @param aControllerPort
9690 * @param aDevice
9691 * @return
9692 */
9693MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9694 IN_BSTR aControllerName,
9695 LONG aControllerPort,
9696 LONG aDevice)
9697{
9698 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9699 it != ll.end();
9700 ++it)
9701 {
9702 MediumAttachment *pAttach = *it;
9703 if (pAttach->matches(aControllerName, aControllerPort, aDevice))
9704 return pAttach;
9705 }
9706
9707 return NULL;
9708}
9709
9710/**
9711 * Looks through the given list of media attachments for one with the given parameters
9712 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9713 * can be searched as well if needed.
9714 *
9715 * @param list
9716 * @param aControllerName
9717 * @param aControllerPort
9718 * @param aDevice
9719 * @return
9720 */
9721MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9722 ComObjPtr<Medium> pMedium)
9723{
9724 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9725 it != ll.end();
9726 ++it)
9727 {
9728 MediumAttachment *pAttach = *it;
9729 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9730 if (pMediumThis == pMedium)
9731 return pAttach;
9732 }
9733
9734 return NULL;
9735}
9736
9737/**
9738 * Looks through the given list of media attachments for one with the given parameters
9739 * and returns it, or NULL if not found. The list is a parameter so that backup lists
9740 * can be searched as well if needed.
9741 *
9742 * @param list
9743 * @param aControllerName
9744 * @param aControllerPort
9745 * @param aDevice
9746 * @return
9747 */
9748MediumAttachment* Machine::findAttachment(const MediaData::AttachmentList &ll,
9749 Guid &id)
9750{
9751 for (MediaData::AttachmentList::const_iterator it = ll.begin();
9752 it != ll.end();
9753 ++it)
9754 {
9755 MediumAttachment *pAttach = *it;
9756 ComObjPtr<Medium> pMediumThis = pAttach->getMedium();
9757 if (pMediumThis->getId() == id)
9758 return pAttach;
9759 }
9760
9761 return NULL;
9762}
9763
9764/**
9765 * Main implementation for Machine::DetachDevice. This also gets called
9766 * from Machine::prepareUnregister() so it has been taken out for simplicity.
9767 *
9768 * @param pAttach Medium attachment to detach.
9769 * @param writeLock Machine write lock which the caller must have locked once. This may be released temporarily in here.
9770 * @param pSnapshot If NULL, then the detachment is for the current machine. Otherwise this is for a SnapshotMachine, and this must be its snapshot.
9771 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs to receive the registry IDs that need saving
9772 * @return
9773 */
9774HRESULT Machine::detachDevice(MediumAttachment *pAttach,
9775 AutoWriteLock &writeLock,
9776 Snapshot *pSnapshot,
9777 GuidList *pllRegistriesThatNeedSaving)
9778{
9779 ComObjPtr<Medium> oldmedium = pAttach->getMedium();
9780 DeviceType_T mediumType = pAttach->getType();
9781
9782 LogFlowThisFunc(("Entering, medium of attachment is %s\n", oldmedium ? oldmedium->getLocationFull().c_str() : "NULL"));
9783
9784 if (pAttach->isImplicit())
9785 {
9786 /* attempt to implicitly delete the implicitly created diff */
9787
9788 /// @todo move the implicit flag from MediumAttachment to Medium
9789 /// and forbid any hard disk operation when it is implicit. Or maybe
9790 /// a special media state for it to make it even more simple.
9791
9792 Assert(mMediaData.isBackedUp());
9793
9794 /* will leave the lock before the potentially lengthy operation, so
9795 * protect with the special state */
9796 MachineState_T oldState = mData->mMachineState;
9797 setMachineState(MachineState_SettingUp);
9798
9799 writeLock.release();
9800
9801 HRESULT rc = oldmedium->deleteStorage(NULL /*aProgress*/,
9802 true /*aWait*/,
9803 pllRegistriesThatNeedSaving);
9804
9805 writeLock.acquire();
9806
9807 setMachineState(oldState);
9808
9809 if (FAILED(rc)) return rc;
9810 }
9811
9812 setModified(IsModified_Storage);
9813 mMediaData.backup();
9814
9815 // we cannot use erase (it) below because backup() above will create
9816 // a copy of the list and make this copy active, but the iterator
9817 // still refers to the original and is not valid for the copy
9818 mMediaData->mAttachments.remove(pAttach);
9819
9820 if (!oldmedium.isNull())
9821 {
9822 // if this is from a snapshot, do not defer detachment to commitMedia()
9823 if (pSnapshot)
9824 oldmedium->removeBackReference(mData->mUuid, pSnapshot->getId());
9825 // else if non-hard disk media, do not defer detachment to commitMedia() either
9826 else if (mediumType != DeviceType_HardDisk)
9827 oldmedium->removeBackReference(mData->mUuid);
9828 }
9829
9830 return S_OK;
9831}
9832
9833/**
9834 * Goes thru all media of the given list and
9835 *
9836 * 1) calls detachDevice() on each of them for this machine and
9837 * 2) adds all Medium objects found in the process to the given list,
9838 * depending on cleanupMode.
9839 *
9840 * If cleanupMode is CleanupMode_DetachAllReturnHardDisksOnly, this only
9841 * adds hard disks to the list. If it is CleanupMode_Full, this adds all
9842 * media to the list.
9843 *
9844 * This gets called from Machine::Unregister, both for the actual Machine and
9845 * the SnapshotMachine objects that might be found in the snapshots.
9846 *
9847 * Requires caller and locking. The machine lock must be passed in because it
9848 * will be passed on to detachDevice which needs it for temporary unlocking.
9849 *
9850 * @param writeLock Machine lock from top-level caller; this gets passed to detachDevice.
9851 * @param pSnapshot Must be NULL when called for a "real" Machine or a snapshot object if called for a SnapshotMachine.
9852 * @param cleanupMode If DetachAllReturnHardDisksOnly, only hard disk media get added to llMedia; if Full, then all media get added;
9853 * otherwise no media get added.
9854 * @param llMedia Caller's list to receive Medium objects which got detached so caller can close() them, depending on cleanupMode.
9855 * @return
9856 */
9857HRESULT Machine::detachAllMedia(AutoWriteLock &writeLock,
9858 Snapshot *pSnapshot,
9859 CleanupMode_T cleanupMode,
9860 MediaList &llMedia)
9861{
9862 Assert(isWriteLockOnCurrentThread());
9863
9864 HRESULT rc;
9865
9866 // make a temporary list because detachDevice invalidates iterators into
9867 // mMediaData->mAttachments
9868 MediaData::AttachmentList llAttachments2 = mMediaData->mAttachments;
9869
9870 for (MediaData::AttachmentList::iterator it = llAttachments2.begin();
9871 it != llAttachments2.end();
9872 ++it)
9873 {
9874 ComObjPtr<MediumAttachment> &pAttach = *it;
9875 ComObjPtr<Medium> pMedium = pAttach->getMedium();
9876
9877 if (!pMedium.isNull())
9878 {
9879 AutoCaller mac(pMedium);
9880 if (FAILED(mac.rc())) return mac.rc();
9881 AutoReadLock lock(pMedium COMMA_LOCKVAL_SRC_POS);
9882 DeviceType_T devType = pMedium->getDeviceType();
9883 if ( ( cleanupMode == CleanupMode_DetachAllReturnHardDisksOnly
9884 && devType == DeviceType_HardDisk)
9885 || (cleanupMode == CleanupMode_Full)
9886 )
9887 {
9888 llMedia.push_back(pMedium);
9889 ComObjPtr<Medium> pParent = pMedium->getParent();
9890 /*
9891 * Search for medias which are not attached to any machine, but
9892 * in the chain to an attached disk. Mediums are only consided
9893 * if they are:
9894 * - have only one child
9895 * - no references to any machines
9896 * - are of normal medium type
9897 */
9898 while (!pParent.isNull())
9899 {
9900 AutoCaller mac1(pParent);
9901 if (FAILED(mac1.rc())) return mac1.rc();
9902 AutoReadLock lock1(pParent COMMA_LOCKVAL_SRC_POS);
9903 if (pParent->getChildren().size() == 1)
9904 {
9905 if ( pParent->getMachineBackRefCount() == 0
9906 && pParent->getType() == MediumType_Normal
9907 && find(llMedia.begin(), llMedia.end(), pParent) == llMedia.end())
9908 llMedia.push_back(pParent);
9909 }else
9910 break;
9911 pParent = pParent->getParent();
9912 }
9913 }
9914 }
9915
9916 // real machine: then we need to use the proper method
9917 rc = detachDevice(pAttach,
9918 writeLock,
9919 pSnapshot,
9920 NULL /* pfNeedsSaveSettings */);
9921
9922 if (FAILED(rc))
9923 return rc;
9924 }
9925
9926 return S_OK;
9927}
9928
9929/**
9930 * Perform deferred hard disk detachments.
9931 *
9932 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
9933 * backed up).
9934 *
9935 * If @a aOnline is @c true then this method will also unlock the old hard disks
9936 * for which the new implicit diffs were created and will lock these new diffs for
9937 * writing.
9938 *
9939 * @param aOnline Whether the VM was online prior to this operation.
9940 *
9941 * @note Locks this object for writing!
9942 */
9943void Machine::commitMedia(bool aOnline /*= false*/)
9944{
9945 AutoCaller autoCaller(this);
9946 AssertComRCReturnVoid(autoCaller.rc());
9947
9948 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9949
9950 LogFlowThisFunc(("Entering, aOnline=%d\n", aOnline));
9951
9952 HRESULT rc = S_OK;
9953
9954 /* no attach/detach operations -- nothing to do */
9955 if (!mMediaData.isBackedUp())
9956 return;
9957
9958 MediaData::AttachmentList &oldAtts = mMediaData.backedUpData()->mAttachments;
9959 bool fMediaNeedsLocking = false;
9960
9961 /* enumerate new attachments */
9962 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
9963 it != mMediaData->mAttachments.end();
9964 ++it)
9965 {
9966 MediumAttachment *pAttach = *it;
9967
9968 pAttach->commit();
9969
9970 Medium* pMedium = pAttach->getMedium();
9971 bool fImplicit = pAttach->isImplicit();
9972
9973 LogFlowThisFunc(("Examining current medium '%s' (implicit: %d)\n",
9974 (pMedium) ? pMedium->getName().c_str() : "NULL",
9975 fImplicit));
9976
9977 /** @todo convert all this Machine-based voodoo to MediumAttachment
9978 * based commit logic. */
9979 if (fImplicit)
9980 {
9981 /* convert implicit attachment to normal */
9982 pAttach->setImplicit(false);
9983
9984 if ( aOnline
9985 && pMedium
9986 && pAttach->getType() == DeviceType_HardDisk
9987 )
9988 {
9989 ComObjPtr<Medium> parent = pMedium->getParent();
9990 AutoWriteLock parentLock(parent COMMA_LOCKVAL_SRC_POS);
9991
9992 /* update the appropriate lock list */
9993 MediumLockList *pMediumLockList;
9994 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
9995 AssertComRC(rc);
9996 if (pMediumLockList)
9997 {
9998 /* unlock if there's a need to change the locking */
9999 if (!fMediaNeedsLocking)
10000 {
10001 rc = mData->mSession.mLockedMedia.Unlock();
10002 AssertComRC(rc);
10003 fMediaNeedsLocking = true;
10004 }
10005 rc = pMediumLockList->Update(parent, false);
10006 AssertComRC(rc);
10007 rc = pMediumLockList->Append(pMedium, true);
10008 AssertComRC(rc);
10009 }
10010 }
10011
10012 continue;
10013 }
10014
10015 if (pMedium)
10016 {
10017 /* was this medium attached before? */
10018 for (MediaData::AttachmentList::iterator oldIt = oldAtts.begin();
10019 oldIt != oldAtts.end();
10020 ++oldIt)
10021 {
10022 MediumAttachment *pOldAttach = *oldIt;
10023 if (pOldAttach->getMedium() == pMedium)
10024 {
10025 LogFlowThisFunc(("--> medium '%s' was attached before, will not remove\n", pMedium->getName().c_str()));
10026
10027 /* yes: remove from old to avoid de-association */
10028 oldAtts.erase(oldIt);
10029 break;
10030 }
10031 }
10032 }
10033 }
10034
10035 /* enumerate remaining old attachments and de-associate from the
10036 * current machine state */
10037 for (MediaData::AttachmentList::const_iterator it = oldAtts.begin();
10038 it != oldAtts.end();
10039 ++it)
10040 {
10041 MediumAttachment *pAttach = *it;
10042 Medium* pMedium = pAttach->getMedium();
10043
10044 /* Detach only hard disks, since DVD/floppy media is detached
10045 * instantly in MountMedium. */
10046 if (pAttach->getType() == DeviceType_HardDisk && pMedium)
10047 {
10048 LogFlowThisFunc(("detaching medium '%s' from machine\n", pMedium->getName().c_str()));
10049
10050 /* now de-associate from the current machine state */
10051 rc = pMedium->removeBackReference(mData->mUuid);
10052 AssertComRC(rc);
10053
10054 if (aOnline)
10055 {
10056 /* unlock since medium is not used anymore */
10057 MediumLockList *pMediumLockList;
10058 rc = mData->mSession.mLockedMedia.Get(pAttach, pMediumLockList);
10059 AssertComRC(rc);
10060 if (pMediumLockList)
10061 {
10062 rc = mData->mSession.mLockedMedia.Remove(pAttach);
10063 AssertComRC(rc);
10064 }
10065 }
10066 }
10067 }
10068
10069 /* take media locks again so that the locking state is consistent */
10070 if (fMediaNeedsLocking)
10071 {
10072 Assert(aOnline);
10073 rc = mData->mSession.mLockedMedia.Lock();
10074 AssertComRC(rc);
10075 }
10076
10077 /* commit the hard disk changes */
10078 mMediaData.commit();
10079
10080 if (isSessionMachine())
10081 {
10082 /*
10083 * Update the parent machine to point to the new owner.
10084 * This is necessary because the stored parent will point to the
10085 * session machine otherwise and cause crashes or errors later
10086 * when the session machine gets invalid.
10087 */
10088 /** @todo Change the MediumAttachment class to behave like any other
10089 * class in this regard by creating peer MediumAttachment
10090 * objects for session machines and share the data with the peer
10091 * machine.
10092 */
10093 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10094 it != mMediaData->mAttachments.end();
10095 ++it)
10096 {
10097 (*it)->updateParentMachine(mPeer);
10098 }
10099
10100 /* attach new data to the primary machine and reshare it */
10101 mPeer->mMediaData.attach(mMediaData);
10102 }
10103
10104 return;
10105}
10106
10107/**
10108 * Perform deferred deletion of implicitly created diffs.
10109 *
10110 * Does nothing if the hard disk attachment data (mMediaData) is not changed (not
10111 * backed up).
10112 *
10113 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
10114 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
10115 *
10116 * @note Locks this object for writing!
10117 *
10118 * @todo r=dj this needs a pllRegistriesThatNeedSaving as well
10119 */
10120void Machine::rollbackMedia()
10121{
10122 AutoCaller autoCaller(this);
10123 AssertComRCReturnVoid (autoCaller.rc());
10124
10125 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10126
10127 LogFlowThisFunc(("Entering\n"));
10128
10129 HRESULT rc = S_OK;
10130
10131 /* no attach/detach operations -- nothing to do */
10132 if (!mMediaData.isBackedUp())
10133 return;
10134
10135 /* enumerate new attachments */
10136 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
10137 it != mMediaData->mAttachments.end();
10138 ++it)
10139 {
10140 MediumAttachment *pAttach = *it;
10141 /* Fix up the backrefs for DVD/floppy media. */
10142 if (pAttach->getType() != DeviceType_HardDisk)
10143 {
10144 Medium* pMedium = pAttach->getMedium();
10145 if (pMedium)
10146 {
10147 rc = pMedium->removeBackReference(mData->mUuid);
10148 AssertComRC(rc);
10149 }
10150 }
10151
10152 (*it)->rollback();
10153
10154 pAttach = *it;
10155 /* Fix up the backrefs for DVD/floppy media. */
10156 if (pAttach->getType() != DeviceType_HardDisk)
10157 {
10158 Medium* pMedium = pAttach->getMedium();
10159 if (pMedium)
10160 {
10161 rc = pMedium->addBackReference(mData->mUuid);
10162 AssertComRC(rc);
10163 }
10164 }
10165 }
10166
10167 /** @todo convert all this Machine-based voodoo to MediumAttachment
10168 * based rollback logic. */
10169 // @todo r=dj the below totally fails if this gets called from Machine::rollback(),
10170 // which gets called if Machine::registeredInit() fails...
10171 deleteImplicitDiffs(NULL /*pfNeedsSaveSettings*/);
10172
10173 return;
10174}
10175
10176/**
10177 * Returns true if the settings file is located in the directory named exactly
10178 * as the machine; this means, among other things, that the machine directory
10179 * should be auto-renamed.
10180 *
10181 * @param aSettingsDir if not NULL, the full machine settings file directory
10182 * name will be assigned there.
10183 *
10184 * @note Doesn't lock anything.
10185 * @note Not thread safe (must be called from this object's lock).
10186 */
10187bool Machine::isInOwnDir(Utf8Str *aSettingsDir /* = NULL */) const
10188{
10189 Utf8Str strMachineDirName(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10190 strMachineDirName.stripFilename(); // path/to/machinesfolder/vmname
10191 if (aSettingsDir)
10192 *aSettingsDir = strMachineDirName;
10193 strMachineDirName.stripPath(); // vmname
10194 Utf8Str strConfigFileOnly(mData->m_strConfigFileFull); // path/to/machinesfolder/vmname/vmname.vbox
10195 strConfigFileOnly.stripPath() // vmname.vbox
10196 .stripExt(); // vmname
10197
10198 AssertReturn(!strMachineDirName.isEmpty(), false);
10199 AssertReturn(!strConfigFileOnly.isEmpty(), false);
10200
10201 return strMachineDirName == strConfigFileOnly;
10202}
10203
10204/**
10205 * Discards all changes to machine settings.
10206 *
10207 * @param aNotify Whether to notify the direct session about changes or not.
10208 *
10209 * @note Locks objects for writing!
10210 */
10211void Machine::rollback(bool aNotify)
10212{
10213 AutoCaller autoCaller(this);
10214 AssertComRCReturn(autoCaller.rc(), (void)0);
10215
10216 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10217
10218 if (!mStorageControllers.isNull())
10219 {
10220 if (mStorageControllers.isBackedUp())
10221 {
10222 /* unitialize all new devices (absent in the backed up list). */
10223 StorageControllerList::const_iterator it = mStorageControllers->begin();
10224 StorageControllerList *backedList = mStorageControllers.backedUpData();
10225 while (it != mStorageControllers->end())
10226 {
10227 if ( std::find(backedList->begin(), backedList->end(), *it)
10228 == backedList->end()
10229 )
10230 {
10231 (*it)->uninit();
10232 }
10233 ++it;
10234 }
10235
10236 /* restore the list */
10237 mStorageControllers.rollback();
10238 }
10239
10240 /* rollback any changes to devices after restoring the list */
10241 if (mData->flModifications & IsModified_Storage)
10242 {
10243 StorageControllerList::const_iterator it = mStorageControllers->begin();
10244 while (it != mStorageControllers->end())
10245 {
10246 (*it)->rollback();
10247 ++it;
10248 }
10249 }
10250 }
10251
10252 mUserData.rollback();
10253
10254 mHWData.rollback();
10255
10256 if (mData->flModifications & IsModified_Storage)
10257 rollbackMedia();
10258
10259 if (mBIOSSettings)
10260 mBIOSSettings->rollback();
10261
10262 if (mVRDEServer && (mData->flModifications & IsModified_VRDEServer))
10263 mVRDEServer->rollback();
10264
10265 if (mAudioAdapter)
10266 mAudioAdapter->rollback();
10267
10268 if (mUSBController && (mData->flModifications & IsModified_USB))
10269 mUSBController->rollback();
10270
10271 if (mBandwidthControl && (mData->flModifications & IsModified_BandwidthControl))
10272 mBandwidthControl->rollback();
10273
10274 ComPtr<INetworkAdapter> networkAdapters[RT_ELEMENTS(mNetworkAdapters)];
10275 ComPtr<ISerialPort> serialPorts[RT_ELEMENTS(mSerialPorts)];
10276 ComPtr<IParallelPort> parallelPorts[RT_ELEMENTS(mParallelPorts)];
10277
10278 if (mData->flModifications & IsModified_NetworkAdapters)
10279 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10280 if ( mNetworkAdapters[slot]
10281 && mNetworkAdapters[slot]->isModified())
10282 {
10283 mNetworkAdapters[slot]->rollback();
10284 networkAdapters[slot] = mNetworkAdapters[slot];
10285 }
10286
10287 if (mData->flModifications & IsModified_SerialPorts)
10288 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10289 if ( mSerialPorts[slot]
10290 && mSerialPorts[slot]->isModified())
10291 {
10292 mSerialPorts[slot]->rollback();
10293 serialPorts[slot] = mSerialPorts[slot];
10294 }
10295
10296 if (mData->flModifications & IsModified_ParallelPorts)
10297 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10298 if ( mParallelPorts[slot]
10299 && mParallelPorts[slot]->isModified())
10300 {
10301 mParallelPorts[slot]->rollback();
10302 parallelPorts[slot] = mParallelPorts[slot];
10303 }
10304
10305 if (aNotify)
10306 {
10307 /* inform the direct session about changes */
10308
10309 ComObjPtr<Machine> that = this;
10310 uint32_t flModifications = mData->flModifications;
10311 alock.leave();
10312
10313 if (flModifications & IsModified_SharedFolders)
10314 that->onSharedFolderChange();
10315
10316 if (flModifications & IsModified_VRDEServer)
10317 that->onVRDEServerChange(/* aRestart */ TRUE);
10318 if (flModifications & IsModified_USB)
10319 that->onUSBControllerChange();
10320
10321 for (ULONG slot = 0; slot < RT_ELEMENTS(networkAdapters); slot ++)
10322 if (networkAdapters[slot])
10323 that->onNetworkAdapterChange(networkAdapters[slot], FALSE);
10324 for (ULONG slot = 0; slot < RT_ELEMENTS(serialPorts); slot ++)
10325 if (serialPorts[slot])
10326 that->onSerialPortChange(serialPorts[slot]);
10327 for (ULONG slot = 0; slot < RT_ELEMENTS(parallelPorts); slot ++)
10328 if (parallelPorts[slot])
10329 that->onParallelPortChange(parallelPorts[slot]);
10330
10331 if (flModifications & IsModified_Storage)
10332 that->onStorageControllerChange();
10333
10334#if 0
10335 if (flModifications & IsModified_BandwidthControl)
10336 that->onBandwidthControlChange();
10337#endif
10338 }
10339}
10340
10341/**
10342 * Commits all the changes to machine settings.
10343 *
10344 * Note that this operation is supposed to never fail.
10345 *
10346 * @note Locks this object and children for writing.
10347 */
10348void Machine::commit()
10349{
10350 AutoCaller autoCaller(this);
10351 AssertComRCReturnVoid(autoCaller.rc());
10352
10353 AutoCaller peerCaller(mPeer);
10354 AssertComRCReturnVoid(peerCaller.rc());
10355
10356 AutoMultiWriteLock2 alock(mPeer, this COMMA_LOCKVAL_SRC_POS);
10357
10358 /*
10359 * use safe commit to ensure Snapshot machines (that share mUserData)
10360 * will still refer to a valid memory location
10361 */
10362 mUserData.commitCopy();
10363
10364 mHWData.commit();
10365
10366 if (mMediaData.isBackedUp())
10367 commitMedia();
10368
10369 mBIOSSettings->commit();
10370 mVRDEServer->commit();
10371 mAudioAdapter->commit();
10372 mUSBController->commit();
10373 mBandwidthControl->commit();
10374
10375 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10376 mNetworkAdapters[slot]->commit();
10377 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10378 mSerialPorts[slot]->commit();
10379 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10380 mParallelPorts[slot]->commit();
10381
10382 bool commitStorageControllers = false;
10383
10384 if (mStorageControllers.isBackedUp())
10385 {
10386 mStorageControllers.commit();
10387
10388 if (mPeer)
10389 {
10390 AutoWriteLock peerlock(mPeer COMMA_LOCKVAL_SRC_POS);
10391
10392 /* Commit all changes to new controllers (this will reshare data with
10393 * peers for those who have peers) */
10394 StorageControllerList *newList = new StorageControllerList();
10395 StorageControllerList::const_iterator it = mStorageControllers->begin();
10396 while (it != mStorageControllers->end())
10397 {
10398 (*it)->commit();
10399
10400 /* look if this controller has a peer device */
10401 ComObjPtr<StorageController> peer = (*it)->getPeer();
10402 if (!peer)
10403 {
10404 /* no peer means the device is a newly created one;
10405 * create a peer owning data this device share it with */
10406 peer.createObject();
10407 peer->init(mPeer, *it, true /* aReshare */);
10408 }
10409 else
10410 {
10411 /* remove peer from the old list */
10412 mPeer->mStorageControllers->remove(peer);
10413 }
10414 /* and add it to the new list */
10415 newList->push_back(peer);
10416
10417 ++it;
10418 }
10419
10420 /* uninit old peer's controllers that are left */
10421 it = mPeer->mStorageControllers->begin();
10422 while (it != mPeer->mStorageControllers->end())
10423 {
10424 (*it)->uninit();
10425 ++it;
10426 }
10427
10428 /* attach new list of controllers to our peer */
10429 mPeer->mStorageControllers.attach(newList);
10430 }
10431 else
10432 {
10433 /* we have no peer (our parent is the newly created machine);
10434 * just commit changes to devices */
10435 commitStorageControllers = true;
10436 }
10437 }
10438 else
10439 {
10440 /* the list of controllers itself is not changed,
10441 * just commit changes to controllers themselves */
10442 commitStorageControllers = true;
10443 }
10444
10445 if (commitStorageControllers)
10446 {
10447 StorageControllerList::const_iterator it = mStorageControllers->begin();
10448 while (it != mStorageControllers->end())
10449 {
10450 (*it)->commit();
10451 ++it;
10452 }
10453 }
10454
10455 if (isSessionMachine())
10456 {
10457 /* attach new data to the primary machine and reshare it */
10458 mPeer->mUserData.attach(mUserData);
10459 mPeer->mHWData.attach(mHWData);
10460 /* mMediaData is reshared by fixupMedia */
10461 // mPeer->mMediaData.attach(mMediaData);
10462 Assert(mPeer->mMediaData.data() == mMediaData.data());
10463 }
10464}
10465
10466/**
10467 * Copies all the hardware data from the given machine.
10468 *
10469 * Currently, only called when the VM is being restored from a snapshot. In
10470 * particular, this implies that the VM is not running during this method's
10471 * call.
10472 *
10473 * @note This method must be called from under this object's lock.
10474 *
10475 * @note This method doesn't call #commit(), so all data remains backed up and
10476 * unsaved.
10477 */
10478void Machine::copyFrom(Machine *aThat)
10479{
10480 AssertReturnVoid(!isSnapshotMachine());
10481 AssertReturnVoid(aThat->isSnapshotMachine());
10482
10483 AssertReturnVoid(!Global::IsOnline(mData->mMachineState));
10484
10485 mHWData.assignCopy(aThat->mHWData);
10486
10487 // create copies of all shared folders (mHWData after attaching a copy
10488 // contains just references to original objects)
10489 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
10490 it != mHWData->mSharedFolders.end();
10491 ++it)
10492 {
10493 ComObjPtr<SharedFolder> folder;
10494 folder.createObject();
10495 HRESULT rc = folder->initCopy(getMachine(), *it);
10496 AssertComRC(rc);
10497 *it = folder;
10498 }
10499
10500 mBIOSSettings->copyFrom(aThat->mBIOSSettings);
10501 mVRDEServer->copyFrom(aThat->mVRDEServer);
10502 mAudioAdapter->copyFrom(aThat->mAudioAdapter);
10503 mUSBController->copyFrom(aThat->mUSBController);
10504 mBandwidthControl->copyFrom(aThat->mBandwidthControl);
10505
10506 /* create private copies of all controllers */
10507 mStorageControllers.backup();
10508 mStorageControllers->clear();
10509 for (StorageControllerList::iterator it = aThat->mStorageControllers->begin();
10510 it != aThat->mStorageControllers->end();
10511 ++it)
10512 {
10513 ComObjPtr<StorageController> ctrl;
10514 ctrl.createObject();
10515 ctrl->initCopy(this, *it);
10516 mStorageControllers->push_back(ctrl);
10517 }
10518
10519 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10520 mNetworkAdapters[slot]->copyFrom(aThat->mNetworkAdapters[slot]);
10521 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10522 mSerialPorts[slot]->copyFrom(aThat->mSerialPorts[slot]);
10523 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10524 mParallelPorts[slot]->copyFrom(aThat->mParallelPorts[slot]);
10525}
10526
10527/**
10528 * Returns whether the given storage controller is hotplug capable.
10529 *
10530 * @returns true if the controller supports hotplugging
10531 * false otherwise.
10532 * @param enmCtrlType The controller type to check for.
10533 */
10534bool Machine::isControllerHotplugCapable(StorageControllerType_T enmCtrlType)
10535{
10536 switch (enmCtrlType)
10537 {
10538 case StorageControllerType_IntelAhci:
10539 return true;
10540 case StorageControllerType_LsiLogic:
10541 case StorageControllerType_LsiLogicSas:
10542 case StorageControllerType_BusLogic:
10543 case StorageControllerType_PIIX3:
10544 case StorageControllerType_PIIX4:
10545 case StorageControllerType_ICH6:
10546 case StorageControllerType_I82078:
10547 default:
10548 return false;
10549 }
10550}
10551
10552#ifdef VBOX_WITH_RESOURCE_USAGE_API
10553
10554void Machine::registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid)
10555{
10556 AssertReturnVoid(isWriteLockOnCurrentThread());
10557 AssertPtrReturnVoid(aCollector);
10558
10559 pm::CollectorHAL *hal = aCollector->getHAL();
10560 /* Create sub metrics */
10561 pm::SubMetric *cpuLoadUser = new pm::SubMetric("CPU/Load/User",
10562 "Percentage of processor time spent in user mode by the VM process.");
10563 pm::SubMetric *cpuLoadKernel = new pm::SubMetric("CPU/Load/Kernel",
10564 "Percentage of processor time spent in kernel mode by the VM process.");
10565 pm::SubMetric *ramUsageUsed = new pm::SubMetric("RAM/Usage/Used",
10566 "Size of resident portion of VM process in memory.");
10567 /* Create and register base metrics */
10568 pm::BaseMetric *cpuLoad = new pm::MachineCpuLoadRaw(hal, aMachine, pid,
10569 cpuLoadUser, cpuLoadKernel);
10570 aCollector->registerBaseMetric(cpuLoad);
10571 pm::BaseMetric *ramUsage = new pm::MachineRamUsage(hal, aMachine, pid,
10572 ramUsageUsed);
10573 aCollector->registerBaseMetric(ramUsage);
10574
10575 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser, 0));
10576 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10577 new pm::AggregateAvg()));
10578 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10579 new pm::AggregateMin()));
10580 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadUser,
10581 new pm::AggregateMax()));
10582 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel, 0));
10583 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10584 new pm::AggregateAvg()));
10585 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10586 new pm::AggregateMin()));
10587 aCollector->registerMetric(new pm::Metric(cpuLoad, cpuLoadKernel,
10588 new pm::AggregateMax()));
10589
10590 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed, 0));
10591 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10592 new pm::AggregateAvg()));
10593 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10594 new pm::AggregateMin()));
10595 aCollector->registerMetric(new pm::Metric(ramUsage, ramUsageUsed,
10596 new pm::AggregateMax()));
10597
10598
10599 /* Guest metrics collector */
10600 mCollectorGuest = new pm::CollectorGuest(aMachine, pid);
10601 aCollector->registerGuest(mCollectorGuest);
10602 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10603 this, __PRETTY_FUNCTION__, mCollectorGuest));
10604
10605 /* Create sub metrics */
10606 pm::SubMetric *guestLoadUser = new pm::SubMetric("Guest/CPU/Load/User",
10607 "Percentage of processor time spent in user mode as seen by the guest.");
10608 pm::SubMetric *guestLoadKernel = new pm::SubMetric("Guest/CPU/Load/Kernel",
10609 "Percentage of processor time spent in kernel mode as seen by the guest.");
10610 pm::SubMetric *guestLoadIdle = new pm::SubMetric("Guest/CPU/Load/Idle",
10611 "Percentage of processor time spent idling as seen by the guest.");
10612
10613 /* The total amount of physical ram is fixed now, but we'll support dynamic guest ram configurations in the future. */
10614 pm::SubMetric *guestMemTotal = new pm::SubMetric("Guest/RAM/Usage/Total", "Total amount of physical guest RAM.");
10615 pm::SubMetric *guestMemFree = new pm::SubMetric("Guest/RAM/Usage/Free", "Free amount of physical guest RAM.");
10616 pm::SubMetric *guestMemBalloon = new pm::SubMetric("Guest/RAM/Usage/Balloon", "Amount of ballooned physical guest RAM.");
10617 pm::SubMetric *guestMemShared = new pm::SubMetric("Guest/RAM/Usage/Shared", "Amount of shared physical guest RAM.");
10618 pm::SubMetric *guestMemCache = new pm::SubMetric("Guest/RAM/Usage/Cache", "Total amount of guest (disk) cache memory.");
10619
10620 pm::SubMetric *guestPagedTotal = new pm::SubMetric("Guest/Pagefile/Usage/Total", "Total amount of space in the page file.");
10621
10622 /* Create and register base metrics */
10623 pm::BaseMetric *guestCpuLoad = new pm::GuestCpuLoad(mCollectorGuest, aMachine,
10624 guestLoadUser, guestLoadKernel, guestLoadIdle);
10625 aCollector->registerBaseMetric(guestCpuLoad);
10626
10627 pm::BaseMetric *guestCpuMem = new pm::GuestRamUsage(mCollectorGuest, aMachine,
10628 guestMemTotal, guestMemFree,
10629 guestMemBalloon, guestMemShared,
10630 guestMemCache, guestPagedTotal);
10631 aCollector->registerBaseMetric(guestCpuMem);
10632
10633 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, 0));
10634 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateAvg()));
10635 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMin()));
10636 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadUser, new pm::AggregateMax()));
10637
10638 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, 0));
10639 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateAvg()));
10640 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMin()));
10641 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadKernel, new pm::AggregateMax()));
10642
10643 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, 0));
10644 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateAvg()));
10645 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMin()));
10646 aCollector->registerMetric(new pm::Metric(guestCpuLoad, guestLoadIdle, new pm::AggregateMax()));
10647
10648 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, 0));
10649 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateAvg()));
10650 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMin()));
10651 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemTotal, new pm::AggregateMax()));
10652
10653 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, 0));
10654 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateAvg()));
10655 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMin()));
10656 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemFree, new pm::AggregateMax()));
10657
10658 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, 0));
10659 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateAvg()));
10660 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMin()));
10661 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemBalloon, new pm::AggregateMax()));
10662
10663 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, 0));
10664 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateAvg()));
10665 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMin()));
10666 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemShared, new pm::AggregateMax()));
10667
10668 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, 0));
10669 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateAvg()));
10670 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMin()));
10671 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestMemCache, new pm::AggregateMax()));
10672
10673 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, 0));
10674 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateAvg()));
10675 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMin()));
10676 aCollector->registerMetric(new pm::Metric(guestCpuMem, guestPagedTotal, new pm::AggregateMax()));
10677}
10678
10679void Machine::unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine)
10680{
10681 AssertReturnVoid(isWriteLockOnCurrentThread());
10682
10683 if (aCollector)
10684 {
10685 aCollector->unregisterMetricsFor(aMachine);
10686 aCollector->unregisterBaseMetricsFor(aMachine);
10687 }
10688}
10689
10690#endif /* VBOX_WITH_RESOURCE_USAGE_API */
10691
10692
10693////////////////////////////////////////////////////////////////////////////////
10694
10695DEFINE_EMPTY_CTOR_DTOR(SessionMachine)
10696
10697HRESULT SessionMachine::FinalConstruct()
10698{
10699 LogFlowThisFunc(("\n"));
10700
10701#if defined(RT_OS_WINDOWS)
10702 mIPCSem = NULL;
10703#elif defined(RT_OS_OS2)
10704 mIPCSem = NULLHANDLE;
10705#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10706 mIPCSem = -1;
10707#else
10708# error "Port me!"
10709#endif
10710
10711 return BaseFinalConstruct();
10712}
10713
10714void SessionMachine::FinalRelease()
10715{
10716 LogFlowThisFunc(("\n"));
10717
10718 uninit(Uninit::Unexpected);
10719
10720 BaseFinalRelease();
10721}
10722
10723/**
10724 * @note Must be called only by Machine::openSession() from its own write lock.
10725 */
10726HRESULT SessionMachine::init(Machine *aMachine)
10727{
10728 LogFlowThisFuncEnter();
10729 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
10730
10731 AssertReturn(aMachine, E_INVALIDARG);
10732
10733 AssertReturn(aMachine->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
10734
10735 /* Enclose the state transition NotReady->InInit->Ready */
10736 AutoInitSpan autoInitSpan(this);
10737 AssertReturn(autoInitSpan.isOk(), E_FAIL);
10738
10739 /* create the interprocess semaphore */
10740#if defined(RT_OS_WINDOWS)
10741 mIPCSemName = aMachine->mData->m_strConfigFileFull;
10742 for (size_t i = 0; i < mIPCSemName.length(); i++)
10743 if (mIPCSemName.raw()[i] == '\\')
10744 mIPCSemName.raw()[i] = '/';
10745 mIPCSem = ::CreateMutex(NULL, FALSE, mIPCSemName.raw());
10746 ComAssertMsgRet(mIPCSem,
10747 ("Cannot create IPC mutex '%ls', err=%d",
10748 mIPCSemName.raw(), ::GetLastError()),
10749 E_FAIL);
10750#elif defined(RT_OS_OS2)
10751 Utf8Str ipcSem = Utf8StrFmt("\\SEM32\\VBOX\\VM\\{%RTuuid}",
10752 aMachine->mData->mUuid.raw());
10753 mIPCSemName = ipcSem;
10754 APIRET arc = ::DosCreateMutexSem((PSZ)ipcSem.c_str(), &mIPCSem, 0, FALSE);
10755 ComAssertMsgRet(arc == NO_ERROR,
10756 ("Cannot create IPC mutex '%s', arc=%ld",
10757 ipcSem.c_str(), arc),
10758 E_FAIL);
10759#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10760# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10761# if defined(RT_OS_FREEBSD) && (HC_ARCH_BITS == 64)
10762 /** @todo Check that this still works correctly. */
10763 AssertCompileSize(key_t, 8);
10764# else
10765 AssertCompileSize(key_t, 4);
10766# endif
10767 key_t key;
10768 mIPCSem = -1;
10769 mIPCKey = "0";
10770 for (uint32_t i = 0; i < 1 << 24; i++)
10771 {
10772 key = ((uint32_t)'V' << 24) | i;
10773 int sem = ::semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
10774 if (sem >= 0 || (errno != EEXIST && errno != EACCES))
10775 {
10776 mIPCSem = sem;
10777 if (sem >= 0)
10778 mIPCKey = BstrFmt("%u", key);
10779 break;
10780 }
10781 }
10782# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10783 Utf8Str semName = aMachine->mData->m_strConfigFileFull;
10784 char *pszSemName = NULL;
10785 RTStrUtf8ToCurrentCP(&pszSemName, semName);
10786 key_t key = ::ftok(pszSemName, 'V');
10787 RTStrFree(pszSemName);
10788
10789 mIPCSem = ::semget(key, 1, S_IRWXU | S_IRWXG | S_IRWXO | IPC_CREAT);
10790# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
10791
10792 int errnoSave = errno;
10793 if (mIPCSem < 0 && errnoSave == ENOSYS)
10794 {
10795 setError(E_FAIL,
10796 tr("Cannot create IPC semaphore. Most likely your host kernel lacks "
10797 "support for SysV IPC. Check the host kernel configuration for "
10798 "CONFIG_SYSVIPC=y"));
10799 return E_FAIL;
10800 }
10801 /* ENOSPC can also be the result of VBoxSVC crashes without properly freeing
10802 * the IPC semaphores */
10803 if (mIPCSem < 0 && errnoSave == ENOSPC)
10804 {
10805#ifdef RT_OS_LINUX
10806 setError(E_FAIL,
10807 tr("Cannot create IPC semaphore because the system limit for the "
10808 "maximum number of semaphore sets (SEMMNI), or the system wide "
10809 "maximum number of semaphores (SEMMNS) would be exceeded. The "
10810 "current set of SysV IPC semaphores can be determined from "
10811 "the file /proc/sysvipc/sem"));
10812#else
10813 setError(E_FAIL,
10814 tr("Cannot create IPC semaphore because the system-imposed limit "
10815 "on the maximum number of allowed semaphores or semaphore "
10816 "identifiers system-wide would be exceeded"));
10817#endif
10818 return E_FAIL;
10819 }
10820 ComAssertMsgRet(mIPCSem >= 0, ("Cannot create IPC semaphore, errno=%d", errnoSave),
10821 E_FAIL);
10822 /* set the initial value to 1 */
10823 int rv = ::semctl(mIPCSem, 0, SETVAL, 1);
10824 ComAssertMsgRet(rv == 0, ("Cannot init IPC semaphore, errno=%d", errno),
10825 E_FAIL);
10826#else
10827# error "Port me!"
10828#endif
10829
10830 /* memorize the peer Machine */
10831 unconst(mPeer) = aMachine;
10832 /* share the parent pointer */
10833 unconst(mParent) = aMachine->mParent;
10834
10835 /* take the pointers to data to share */
10836 mData.share(aMachine->mData);
10837 mSSData.share(aMachine->mSSData);
10838
10839 mUserData.share(aMachine->mUserData);
10840 mHWData.share(aMachine->mHWData);
10841 mMediaData.share(aMachine->mMediaData);
10842
10843 mStorageControllers.allocate();
10844 for (StorageControllerList::const_iterator it = aMachine->mStorageControllers->begin();
10845 it != aMachine->mStorageControllers->end();
10846 ++it)
10847 {
10848 ComObjPtr<StorageController> ctl;
10849 ctl.createObject();
10850 ctl->init(this, *it);
10851 mStorageControllers->push_back(ctl);
10852 }
10853
10854 unconst(mBIOSSettings).createObject();
10855 mBIOSSettings->init(this, aMachine->mBIOSSettings);
10856 /* create another VRDEServer object that will be mutable */
10857 unconst(mVRDEServer).createObject();
10858 mVRDEServer->init(this, aMachine->mVRDEServer);
10859 /* create another audio adapter object that will be mutable */
10860 unconst(mAudioAdapter).createObject();
10861 mAudioAdapter->init(this, aMachine->mAudioAdapter);
10862 /* create a list of serial ports that will be mutable */
10863 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
10864 {
10865 unconst(mSerialPorts[slot]).createObject();
10866 mSerialPorts[slot]->init(this, aMachine->mSerialPorts[slot]);
10867 }
10868 /* create a list of parallel ports that will be mutable */
10869 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
10870 {
10871 unconst(mParallelPorts[slot]).createObject();
10872 mParallelPorts[slot]->init(this, aMachine->mParallelPorts[slot]);
10873 }
10874 /* create another USB controller object that will be mutable */
10875 unconst(mUSBController).createObject();
10876 mUSBController->init(this, aMachine->mUSBController);
10877
10878 /* create a list of network adapters that will be mutable */
10879 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
10880 {
10881 unconst(mNetworkAdapters[slot]).createObject();
10882 mNetworkAdapters[slot]->init(this, aMachine->mNetworkAdapters[slot]);
10883 }
10884
10885 /* create another bandwidth control object that will be mutable */
10886 unconst(mBandwidthControl).createObject();
10887 mBandwidthControl->init(this, aMachine->mBandwidthControl);
10888
10889 /* default is to delete saved state on Saved -> PoweredOff transition */
10890 mRemoveSavedState = true;
10891
10892 /* Confirm a successful initialization when it's the case */
10893 autoInitSpan.setSucceeded();
10894
10895 LogFlowThisFuncLeave();
10896 return S_OK;
10897}
10898
10899/**
10900 * Uninitializes this session object. If the reason is other than
10901 * Uninit::Unexpected, then this method MUST be called from #checkForDeath().
10902 *
10903 * @param aReason uninitialization reason
10904 *
10905 * @note Locks mParent + this object for writing.
10906 */
10907void SessionMachine::uninit(Uninit::Reason aReason)
10908{
10909 LogFlowThisFuncEnter();
10910 LogFlowThisFunc(("reason=%d\n", aReason));
10911
10912 /*
10913 * Strongly reference ourselves to prevent this object deletion after
10914 * mData->mSession.mMachine.setNull() below (which can release the last
10915 * reference and call the destructor). Important: this must be done before
10916 * accessing any members (and before AutoUninitSpan that does it as well).
10917 * This self reference will be released as the very last step on return.
10918 */
10919 ComObjPtr<SessionMachine> selfRef = this;
10920
10921 /* Enclose the state transition Ready->InUninit->NotReady */
10922 AutoUninitSpan autoUninitSpan(this);
10923 if (autoUninitSpan.uninitDone())
10924 {
10925 LogFlowThisFunc(("Already uninitialized\n"));
10926 LogFlowThisFuncLeave();
10927 return;
10928 }
10929
10930 if (autoUninitSpan.initFailed())
10931 {
10932 /* We've been called by init() because it's failed. It's not really
10933 * necessary (nor it's safe) to perform the regular uninit sequence
10934 * below, the following is enough.
10935 */
10936 LogFlowThisFunc(("Initialization failed.\n"));
10937#if defined(RT_OS_WINDOWS)
10938 if (mIPCSem)
10939 ::CloseHandle(mIPCSem);
10940 mIPCSem = NULL;
10941#elif defined(RT_OS_OS2)
10942 if (mIPCSem != NULLHANDLE)
10943 ::DosCloseMutexSem(mIPCSem);
10944 mIPCSem = NULLHANDLE;
10945#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
10946 if (mIPCSem >= 0)
10947 ::semctl(mIPCSem, 0, IPC_RMID);
10948 mIPCSem = -1;
10949# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
10950 mIPCKey = "0";
10951# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
10952#else
10953# error "Port me!"
10954#endif
10955 uninitDataAndChildObjects();
10956 mData.free();
10957 unconst(mParent) = NULL;
10958 unconst(mPeer) = NULL;
10959 LogFlowThisFuncLeave();
10960 return;
10961 }
10962
10963 MachineState_T lastState;
10964 {
10965 AutoReadLock tempLock(this COMMA_LOCKVAL_SRC_POS);
10966 lastState = mData->mMachineState;
10967 }
10968 NOREF(lastState);
10969
10970#ifdef VBOX_WITH_USB
10971 // release all captured USB devices, but do this before requesting the locks below
10972 if (aReason == Uninit::Abnormal && Global::IsOnline(lastState))
10973 {
10974 /* Console::captureUSBDevices() is called in the VM process only after
10975 * setting the machine state to Starting or Restoring.
10976 * Console::detachAllUSBDevices() will be called upon successful
10977 * termination. So, we need to release USB devices only if there was
10978 * an abnormal termination of a running VM.
10979 *
10980 * This is identical to SessionMachine::DetachAllUSBDevices except
10981 * for the aAbnormal argument. */
10982 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
10983 AssertComRC(rc);
10984 NOREF(rc);
10985
10986 USBProxyService *service = mParent->host()->usbProxyService();
10987 if (service)
10988 service->detachAllDevicesFromVM(this, true /* aDone */, true /* aAbnormal */);
10989 }
10990#endif /* VBOX_WITH_USB */
10991
10992 // we need to lock this object in uninit() because the lock is shared
10993 // with mPeer (as well as data we modify below). mParent->addProcessToReap()
10994 // and others need mParent lock, and USB needs host lock.
10995 AutoMultiWriteLock3 multilock(mParent, mParent->host(), this COMMA_LOCKVAL_SRC_POS);
10996
10997 LogAleksey(("{%p} " LOG_FN_FMT ": mCollectorGuest=%p\n",
10998 this, __PRETTY_FUNCTION__, mCollectorGuest));
10999 if (mCollectorGuest)
11000 {
11001 mParent->performanceCollector()->unregisterGuest(mCollectorGuest);
11002 // delete mCollectorGuest; => CollectorGuestManager::destroyUnregistered()
11003 mCollectorGuest = NULL;
11004 }
11005#if 0
11006 // Trigger async cleanup tasks, avoid doing things here which are not
11007 // vital to be done immediately and maybe need more locks. This calls
11008 // Machine::unregisterMetrics().
11009 mParent->onMachineUninit(mPeer);
11010#else
11011 /*
11012 * It is safe to call Machine::unregisterMetrics() here because
11013 * PerformanceCollector::samplerCallback no longer accesses guest methods
11014 * holding the lock.
11015 */
11016 unregisterMetrics(mParent->performanceCollector(), mPeer);
11017#endif
11018
11019 if (aReason == Uninit::Abnormal)
11020 {
11021 LogWarningThisFunc(("ABNORMAL client termination! (wasBusy=%d)\n",
11022 Global::IsOnlineOrTransient(lastState)));
11023
11024 /* reset the state to Aborted */
11025 if (mData->mMachineState != MachineState_Aborted)
11026 setMachineState(MachineState_Aborted);
11027 }
11028
11029 // any machine settings modified?
11030 if (mData->flModifications)
11031 {
11032 LogWarningThisFunc(("Discarding unsaved settings changes!\n"));
11033 rollback(false /* aNotify */);
11034 }
11035
11036 Assert( mConsoleTaskData.strStateFilePath.isEmpty()
11037 || !mConsoleTaskData.mSnapshot);
11038 if (!mConsoleTaskData.strStateFilePath.isEmpty())
11039 {
11040 LogWarningThisFunc(("canceling failed save state request!\n"));
11041 endSavingState(E_FAIL, tr("Machine terminated with pending save state!"));
11042 }
11043 else if (!mConsoleTaskData.mSnapshot.isNull())
11044 {
11045 LogWarningThisFunc(("canceling untaken snapshot!\n"));
11046
11047 /* delete all differencing hard disks created (this will also attach
11048 * their parents back by rolling back mMediaData) */
11049 rollbackMedia();
11050
11051 // delete the saved state file (it might have been already created)
11052 // AFTER killing the snapshot so that releaseSavedStateFile() won't
11053 // think it's still in use
11054 Utf8Str strStateFile = mConsoleTaskData.mSnapshot->getStateFilePath();
11055 mConsoleTaskData.mSnapshot->uninit();
11056 releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
11057 }
11058
11059 if (!mData->mSession.mType.isEmpty())
11060 {
11061 /* mType is not null when this machine's process has been started by
11062 * Machine::LaunchVMProcess(), therefore it is our child. We
11063 * need to queue the PID to reap the process (and avoid zombies on
11064 * Linux). */
11065 Assert(mData->mSession.mPid != NIL_RTPROCESS);
11066 mParent->addProcessToReap(mData->mSession.mPid);
11067 }
11068
11069 mData->mSession.mPid = NIL_RTPROCESS;
11070
11071 if (aReason == Uninit::Unexpected)
11072 {
11073 /* Uninitialization didn't come from #checkForDeath(), so tell the
11074 * client watcher thread to update the set of machines that have open
11075 * sessions. */
11076 mParent->updateClientWatcher();
11077 }
11078
11079 /* uninitialize all remote controls */
11080 if (mData->mSession.mRemoteControls.size())
11081 {
11082 LogFlowThisFunc(("Closing remote sessions (%d):\n",
11083 mData->mSession.mRemoteControls.size()));
11084
11085 Data::Session::RemoteControlList::iterator it =
11086 mData->mSession.mRemoteControls.begin();
11087 while (it != mData->mSession.mRemoteControls.end())
11088 {
11089 LogFlowThisFunc((" Calling remoteControl->Uninitialize()...\n"));
11090 HRESULT rc = (*it)->Uninitialize();
11091 LogFlowThisFunc((" remoteControl->Uninitialize() returned %08X\n", rc));
11092 if (FAILED(rc))
11093 LogWarningThisFunc(("Forgot to close the remote session?\n"));
11094 ++it;
11095 }
11096 mData->mSession.mRemoteControls.clear();
11097 }
11098
11099 /*
11100 * An expected uninitialization can come only from #checkForDeath().
11101 * Otherwise it means that something's gone really wrong (for example,
11102 * the Session implementation has released the VirtualBox reference
11103 * before it triggered #OnSessionEnd(), or before releasing IPC semaphore,
11104 * etc). However, it's also possible, that the client releases the IPC
11105 * semaphore correctly (i.e. before it releases the VirtualBox reference),
11106 * but the VirtualBox release event comes first to the server process.
11107 * This case is practically possible, so we should not assert on an
11108 * unexpected uninit, just log a warning.
11109 */
11110
11111 if ((aReason == Uninit::Unexpected))
11112 LogWarningThisFunc(("Unexpected SessionMachine uninitialization!\n"));
11113
11114 if (aReason != Uninit::Normal)
11115 {
11116 mData->mSession.mDirectControl.setNull();
11117 }
11118 else
11119 {
11120 /* this must be null here (see #OnSessionEnd()) */
11121 Assert(mData->mSession.mDirectControl.isNull());
11122 Assert(mData->mSession.mState == SessionState_Unlocking);
11123 Assert(!mData->mSession.mProgress.isNull());
11124 }
11125 if (mData->mSession.mProgress)
11126 {
11127 if (aReason == Uninit::Normal)
11128 mData->mSession.mProgress->notifyComplete(S_OK);
11129 else
11130 mData->mSession.mProgress->notifyComplete(E_FAIL,
11131 COM_IIDOF(ISession),
11132 getComponentName(),
11133 tr("The VM session was aborted"));
11134 mData->mSession.mProgress.setNull();
11135 }
11136
11137 /* remove the association between the peer machine and this session machine */
11138 Assert( (SessionMachine*)mData->mSession.mMachine == this
11139 || aReason == Uninit::Unexpected);
11140
11141 /* reset the rest of session data */
11142 mData->mSession.mMachine.setNull();
11143 mData->mSession.mState = SessionState_Unlocked;
11144 mData->mSession.mType.setNull();
11145
11146 /* close the interprocess semaphore before leaving the exclusive lock */
11147#if defined(RT_OS_WINDOWS)
11148 if (mIPCSem)
11149 ::CloseHandle(mIPCSem);
11150 mIPCSem = NULL;
11151#elif defined(RT_OS_OS2)
11152 if (mIPCSem != NULLHANDLE)
11153 ::DosCloseMutexSem(mIPCSem);
11154 mIPCSem = NULLHANDLE;
11155#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11156 if (mIPCSem >= 0)
11157 ::semctl(mIPCSem, 0, IPC_RMID);
11158 mIPCSem = -1;
11159# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11160 mIPCKey = "0";
11161# endif /* VBOX_WITH_NEW_SYS_V_KEYGEN */
11162#else
11163# error "Port me!"
11164#endif
11165
11166 /* fire an event */
11167 mParent->onSessionStateChange(mData->mUuid, SessionState_Unlocked);
11168
11169 uninitDataAndChildObjects();
11170
11171 /* free the essential data structure last */
11172 mData.free();
11173
11174#if 1 /** @todo Please review this change! (bird) */
11175 /* drop the exclusive lock before setting the below two to NULL */
11176 multilock.release();
11177#else
11178 /* leave the exclusive lock before setting the below two to NULL */
11179 multilock.leave();
11180#endif
11181
11182 unconst(mParent) = NULL;
11183 unconst(mPeer) = NULL;
11184
11185 LogFlowThisFuncLeave();
11186}
11187
11188// util::Lockable interface
11189////////////////////////////////////////////////////////////////////////////////
11190
11191/**
11192 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
11193 * with the primary Machine instance (mPeer).
11194 */
11195RWLockHandle *SessionMachine::lockHandle() const
11196{
11197 AssertReturn(mPeer != NULL, NULL);
11198 return mPeer->lockHandle();
11199}
11200
11201// IInternalMachineControl methods
11202////////////////////////////////////////////////////////////////////////////////
11203
11204/**
11205 * @note Locks this object for writing.
11206 */
11207STDMETHODIMP SessionMachine::SetRemoveSavedStateFile(BOOL aRemove)
11208{
11209 AutoCaller autoCaller(this);
11210 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11211
11212 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11213
11214 mRemoveSavedState = aRemove;
11215
11216 return S_OK;
11217}
11218
11219/**
11220 * @note Locks the same as #setMachineState() does.
11221 */
11222STDMETHODIMP SessionMachine::UpdateState(MachineState_T aMachineState)
11223{
11224 return setMachineState(aMachineState);
11225}
11226
11227/**
11228 * @note Locks this object for reading.
11229 */
11230STDMETHODIMP SessionMachine::GetIPCId(BSTR *aId)
11231{
11232 AutoCaller autoCaller(this);
11233 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11234
11235 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11236
11237#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
11238 mIPCSemName.cloneTo(aId);
11239 return S_OK;
11240#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
11241# ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
11242 mIPCKey.cloneTo(aId);
11243# else /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11244 mData->m_strConfigFileFull.cloneTo(aId);
11245# endif /* !VBOX_WITH_NEW_SYS_V_KEYGEN */
11246 return S_OK;
11247#else
11248# error "Port me!"
11249#endif
11250}
11251
11252/**
11253 * @note Locks this object for writing.
11254 */
11255STDMETHODIMP SessionMachine::BeginPowerUp(IProgress *aProgress)
11256{
11257 LogFlowThisFunc(("aProgress=%p\n", aProgress));
11258 AutoCaller autoCaller(this);
11259 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11260
11261 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11262
11263 if (mData->mSession.mState != SessionState_Locked)
11264 return VBOX_E_INVALID_OBJECT_STATE;
11265
11266 if (!mData->mSession.mProgress.isNull())
11267 mData->mSession.mProgress->setOtherProgressObject(aProgress);
11268
11269 LogFlowThisFunc(("returns S_OK.\n"));
11270 return S_OK;
11271}
11272
11273/**
11274 * @note Locks this object for writing.
11275 */
11276STDMETHODIMP SessionMachine::EndPowerUp(LONG iResult)
11277{
11278 AutoCaller autoCaller(this);
11279 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11280
11281 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11282
11283 if (mData->mSession.mState != SessionState_Locked)
11284 return VBOX_E_INVALID_OBJECT_STATE;
11285
11286 /* Finalize the LaunchVMProcess progress object. */
11287 if (mData->mSession.mProgress)
11288 {
11289 mData->mSession.mProgress->notifyComplete((HRESULT)iResult);
11290 mData->mSession.mProgress.setNull();
11291 }
11292
11293 if (SUCCEEDED((HRESULT)iResult))
11294 {
11295#ifdef VBOX_WITH_RESOURCE_USAGE_API
11296 /* The VM has been powered up successfully, so it makes sense
11297 * now to offer the performance metrics for a running machine
11298 * object. Doing it earlier wouldn't be safe. */
11299 registerMetrics(mParent->performanceCollector(), mPeer,
11300 mData->mSession.mPid);
11301#endif /* VBOX_WITH_RESOURCE_USAGE_API */
11302 }
11303
11304 return S_OK;
11305}
11306
11307/**
11308 * @note Locks this object for writing.
11309 */
11310STDMETHODIMP SessionMachine::BeginPoweringDown(IProgress **aProgress)
11311{
11312 LogFlowThisFuncEnter();
11313
11314 CheckComArgOutPointerValid(aProgress);
11315
11316 AutoCaller autoCaller(this);
11317 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11318
11319 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11320
11321 AssertReturn(mConsoleTaskData.mLastState == MachineState_Null,
11322 E_FAIL);
11323
11324 /* create a progress object to track operation completion */
11325 ComObjPtr<Progress> pProgress;
11326 pProgress.createObject();
11327 pProgress->init(getVirtualBox(),
11328 static_cast<IMachine *>(this) /* aInitiator */,
11329 Bstr(tr("Stopping the virtual machine")).raw(),
11330 FALSE /* aCancelable */);
11331
11332 /* fill in the console task data */
11333 mConsoleTaskData.mLastState = mData->mMachineState;
11334 mConsoleTaskData.mProgress = pProgress;
11335
11336 /* set the state to Stopping (this is expected by Console::PowerDown()) */
11337 setMachineState(MachineState_Stopping);
11338
11339 pProgress.queryInterfaceTo(aProgress);
11340
11341 return S_OK;
11342}
11343
11344/**
11345 * @note Locks this object for writing.
11346 */
11347STDMETHODIMP SessionMachine::EndPoweringDown(LONG iResult, IN_BSTR aErrMsg)
11348{
11349 LogFlowThisFuncEnter();
11350
11351 AutoCaller autoCaller(this);
11352 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11353
11354 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11355
11356 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_PoweredOff)
11357 || (FAILED(iResult) && mData->mMachineState == MachineState_Stopping))
11358 && mConsoleTaskData.mLastState != MachineState_Null,
11359 E_FAIL);
11360
11361 /*
11362 * On failure, set the state to the state we had when BeginPoweringDown()
11363 * was called (this is expected by Console::PowerDown() and the associated
11364 * task). On success the VM process already changed the state to
11365 * MachineState_PoweredOff, so no need to do anything.
11366 */
11367 if (FAILED(iResult))
11368 setMachineState(mConsoleTaskData.mLastState);
11369
11370 /* notify the progress object about operation completion */
11371 Assert(mConsoleTaskData.mProgress);
11372 if (SUCCEEDED(iResult))
11373 mConsoleTaskData.mProgress->notifyComplete(S_OK);
11374 else
11375 {
11376 Utf8Str strErrMsg(aErrMsg);
11377 if (strErrMsg.length())
11378 mConsoleTaskData.mProgress->notifyComplete(iResult,
11379 COM_IIDOF(ISession),
11380 getComponentName(),
11381 strErrMsg.c_str());
11382 else
11383 mConsoleTaskData.mProgress->notifyComplete(iResult);
11384 }
11385
11386 /* clear out the temporary saved state data */
11387 mConsoleTaskData.mLastState = MachineState_Null;
11388 mConsoleTaskData.mProgress.setNull();
11389
11390 LogFlowThisFuncLeave();
11391 return S_OK;
11392}
11393
11394
11395/**
11396 * Goes through the USB filters of the given machine to see if the given
11397 * device matches any filter or not.
11398 *
11399 * @note Locks the same as USBController::hasMatchingFilter() does.
11400 */
11401STDMETHODIMP SessionMachine::RunUSBDeviceFilters(IUSBDevice *aUSBDevice,
11402 BOOL *aMatched,
11403 ULONG *aMaskedIfs)
11404{
11405 LogFlowThisFunc(("\n"));
11406
11407 CheckComArgNotNull(aUSBDevice);
11408 CheckComArgOutPointerValid(aMatched);
11409
11410 AutoCaller autoCaller(this);
11411 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11412
11413#ifdef VBOX_WITH_USB
11414 *aMatched = mUSBController->hasMatchingFilter(aUSBDevice, aMaskedIfs);
11415#else
11416 NOREF(aUSBDevice);
11417 NOREF(aMaskedIfs);
11418 *aMatched = FALSE;
11419#endif
11420
11421 return S_OK;
11422}
11423
11424/**
11425 * @note Locks the same as Host::captureUSBDevice() does.
11426 */
11427STDMETHODIMP SessionMachine::CaptureUSBDevice(IN_BSTR aId)
11428{
11429 LogFlowThisFunc(("\n"));
11430
11431 AutoCaller autoCaller(this);
11432 AssertComRCReturnRC(autoCaller.rc());
11433
11434#ifdef VBOX_WITH_USB
11435 /* if captureDeviceForVM() fails, it must have set extended error info */
11436 clearError();
11437 MultiResult rc = mParent->host()->checkUSBProxyService();
11438 if (FAILED(rc)) return rc;
11439
11440 USBProxyService *service = mParent->host()->usbProxyService();
11441 AssertReturn(service, E_FAIL);
11442 return service->captureDeviceForVM(this, Guid(aId).ref());
11443#else
11444 NOREF(aId);
11445 return E_NOTIMPL;
11446#endif
11447}
11448
11449/**
11450 * @note Locks the same as Host::detachUSBDevice() does.
11451 */
11452STDMETHODIMP SessionMachine::DetachUSBDevice(IN_BSTR aId, BOOL aDone)
11453{
11454 LogFlowThisFunc(("\n"));
11455
11456 AutoCaller autoCaller(this);
11457 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11458
11459#ifdef VBOX_WITH_USB
11460 USBProxyService *service = mParent->host()->usbProxyService();
11461 AssertReturn(service, E_FAIL);
11462 return service->detachDeviceFromVM(this, Guid(aId).ref(), !!aDone);
11463#else
11464 NOREF(aId);
11465 NOREF(aDone);
11466 return E_NOTIMPL;
11467#endif
11468}
11469
11470/**
11471 * Inserts all machine filters to the USB proxy service and then calls
11472 * Host::autoCaptureUSBDevices().
11473 *
11474 * Called by Console from the VM process upon VM startup.
11475 *
11476 * @note Locks what called methods lock.
11477 */
11478STDMETHODIMP SessionMachine::AutoCaptureUSBDevices()
11479{
11480 LogFlowThisFunc(("\n"));
11481
11482 AutoCaller autoCaller(this);
11483 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11484
11485#ifdef VBOX_WITH_USB
11486 HRESULT rc = mUSBController->notifyProxy(true /* aInsertFilters */);
11487 AssertComRC(rc);
11488 NOREF(rc);
11489
11490 USBProxyService *service = mParent->host()->usbProxyService();
11491 AssertReturn(service, E_FAIL);
11492 return service->autoCaptureDevicesForVM(this);
11493#else
11494 return S_OK;
11495#endif
11496}
11497
11498/**
11499 * Removes all machine filters from the USB proxy service and then calls
11500 * Host::detachAllUSBDevices().
11501 *
11502 * Called by Console from the VM process upon normal VM termination or by
11503 * SessionMachine::uninit() upon abnormal VM termination (from under the
11504 * Machine/SessionMachine lock).
11505 *
11506 * @note Locks what called methods lock.
11507 */
11508STDMETHODIMP SessionMachine::DetachAllUSBDevices(BOOL aDone)
11509{
11510 LogFlowThisFunc(("\n"));
11511
11512 AutoCaller autoCaller(this);
11513 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11514
11515#ifdef VBOX_WITH_USB
11516 HRESULT rc = mUSBController->notifyProxy(false /* aInsertFilters */);
11517 AssertComRC(rc);
11518 NOREF(rc);
11519
11520 USBProxyService *service = mParent->host()->usbProxyService();
11521 AssertReturn(service, E_FAIL);
11522 return service->detachAllDevicesFromVM(this, !!aDone, false /* aAbnormal */);
11523#else
11524 NOREF(aDone);
11525 return S_OK;
11526#endif
11527}
11528
11529/**
11530 * @note Locks this object for writing.
11531 */
11532STDMETHODIMP SessionMachine::OnSessionEnd(ISession *aSession,
11533 IProgress **aProgress)
11534{
11535 LogFlowThisFuncEnter();
11536
11537 AssertReturn(aSession, E_INVALIDARG);
11538 AssertReturn(aProgress, E_INVALIDARG);
11539
11540 AutoCaller autoCaller(this);
11541
11542 LogFlowThisFunc(("callerstate=%d\n", autoCaller.state()));
11543 /*
11544 * We don't assert below because it might happen that a non-direct session
11545 * informs us it is closed right after we've been uninitialized -- it's ok.
11546 */
11547 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11548
11549 /* get IInternalSessionControl interface */
11550 ComPtr<IInternalSessionControl> control(aSession);
11551
11552 ComAssertRet(!control.isNull(), E_INVALIDARG);
11553
11554 /* Creating a Progress object requires the VirtualBox lock, and
11555 * thus locking it here is required by the lock order rules. */
11556 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11557
11558 if (control == mData->mSession.mDirectControl)
11559 {
11560 ComAssertRet(aProgress, E_POINTER);
11561
11562 /* The direct session is being normally closed by the client process
11563 * ----------------------------------------------------------------- */
11564
11565 /* go to the closing state (essential for all open*Session() calls and
11566 * for #checkForDeath()) */
11567 Assert(mData->mSession.mState == SessionState_Locked);
11568 mData->mSession.mState = SessionState_Unlocking;
11569
11570 /* set direct control to NULL to release the remote instance */
11571 mData->mSession.mDirectControl.setNull();
11572 LogFlowThisFunc(("Direct control is set to NULL\n"));
11573
11574 if (mData->mSession.mProgress)
11575 {
11576 /* finalize the progress, someone might wait if a frontend
11577 * closes the session before powering on the VM. */
11578 mData->mSession.mProgress->notifyComplete(E_FAIL,
11579 COM_IIDOF(ISession),
11580 getComponentName(),
11581 tr("The VM session was closed before any attempt to power it on"));
11582 mData->mSession.mProgress.setNull();
11583 }
11584
11585 /* Create the progress object the client will use to wait until
11586 * #checkForDeath() is called to uninitialize this session object after
11587 * it releases the IPC semaphore.
11588 * Note! Because we're "reusing" mProgress here, this must be a proxy
11589 * object just like for LaunchVMProcess. */
11590 Assert(mData->mSession.mProgress.isNull());
11591 ComObjPtr<ProgressProxy> progress;
11592 progress.createObject();
11593 ComPtr<IUnknown> pPeer(mPeer);
11594 progress->init(mParent, pPeer,
11595 Bstr(tr("Closing session")).raw(),
11596 FALSE /* aCancelable */);
11597 progress.queryInterfaceTo(aProgress);
11598 mData->mSession.mProgress = progress;
11599 }
11600 else
11601 {
11602 /* the remote session is being normally closed */
11603 Data::Session::RemoteControlList::iterator it =
11604 mData->mSession.mRemoteControls.begin();
11605 while (it != mData->mSession.mRemoteControls.end())
11606 {
11607 if (control == *it)
11608 break;
11609 ++it;
11610 }
11611 BOOL found = it != mData->mSession.mRemoteControls.end();
11612 ComAssertMsgRet(found, ("The session is not found in the session list!"),
11613 E_INVALIDARG);
11614 mData->mSession.mRemoteControls.remove(*it);
11615 }
11616
11617 LogFlowThisFuncLeave();
11618 return S_OK;
11619}
11620
11621/**
11622 * @note Locks this object for writing.
11623 */
11624STDMETHODIMP SessionMachine::BeginSavingState(IProgress **aProgress, BSTR *aStateFilePath)
11625{
11626 LogFlowThisFuncEnter();
11627
11628 CheckComArgOutPointerValid(aProgress);
11629 CheckComArgOutPointerValid(aStateFilePath);
11630
11631 AutoCaller autoCaller(this);
11632 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11633
11634 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11635
11636 AssertReturn( mData->mMachineState == MachineState_Paused
11637 && mConsoleTaskData.mLastState == MachineState_Null
11638 && mConsoleTaskData.strStateFilePath.isEmpty(),
11639 E_FAIL);
11640
11641 /* create a progress object to track operation completion */
11642 ComObjPtr<Progress> pProgress;
11643 pProgress.createObject();
11644 pProgress->init(getVirtualBox(),
11645 static_cast<IMachine *>(this) /* aInitiator */,
11646 Bstr(tr("Saving the execution state of the virtual machine")).raw(),
11647 FALSE /* aCancelable */);
11648
11649 Utf8Str strStateFilePath;
11650 /* stateFilePath is null when the machine is not running */
11651 if (mData->mMachineState == MachineState_Paused)
11652 composeSavedStateFilename(strStateFilePath);
11653
11654 /* fill in the console task data */
11655 mConsoleTaskData.mLastState = mData->mMachineState;
11656 mConsoleTaskData.strStateFilePath = strStateFilePath;
11657 mConsoleTaskData.mProgress = pProgress;
11658
11659 /* set the state to Saving (this is expected by Console::SaveState()) */
11660 setMachineState(MachineState_Saving);
11661
11662 strStateFilePath.cloneTo(aStateFilePath);
11663 pProgress.queryInterfaceTo(aProgress);
11664
11665 return S_OK;
11666}
11667
11668/**
11669 * @note Locks mParent + this object for writing.
11670 */
11671STDMETHODIMP SessionMachine::EndSavingState(LONG iResult, IN_BSTR aErrMsg)
11672{
11673 LogFlowThisFunc(("\n"));
11674
11675 AutoCaller autoCaller(this);
11676 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11677
11678 /* endSavingState() need mParent lock */
11679 AutoMultiWriteLock2 alock(mParent, this COMMA_LOCKVAL_SRC_POS);
11680
11681 AssertReturn( ( (SUCCEEDED(iResult) && mData->mMachineState == MachineState_Saved)
11682 || (FAILED(iResult) && mData->mMachineState == MachineState_Saving))
11683 && mConsoleTaskData.mLastState != MachineState_Null
11684 && !mConsoleTaskData.strStateFilePath.isEmpty(),
11685 E_FAIL);
11686
11687 /*
11688 * On failure, set the state to the state we had when BeginSavingState()
11689 * was called (this is expected by Console::SaveState() and the associated
11690 * task). On success the VM process already changed the state to
11691 * MachineState_Saved, so no need to do anything.
11692 */
11693 if (FAILED(iResult))
11694 setMachineState(mConsoleTaskData.mLastState);
11695
11696 return endSavingState(iResult, aErrMsg);
11697}
11698
11699/**
11700 * @note Locks this object for writing.
11701 */
11702STDMETHODIMP SessionMachine::AdoptSavedState(IN_BSTR aSavedStateFile)
11703{
11704 LogFlowThisFunc(("\n"));
11705
11706 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
11707
11708 AutoCaller autoCaller(this);
11709 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11710
11711 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11712
11713 AssertReturn( mData->mMachineState == MachineState_PoweredOff
11714 || mData->mMachineState == MachineState_Teleported
11715 || mData->mMachineState == MachineState_Aborted
11716 , E_FAIL); /** @todo setError. */
11717
11718 Utf8Str stateFilePathFull = aSavedStateFile;
11719 int vrc = calculateFullPath(stateFilePathFull, stateFilePathFull);
11720 if (RT_FAILURE(vrc))
11721 return setError(VBOX_E_FILE_ERROR,
11722 tr("Invalid saved state file path '%ls' (%Rrc)"),
11723 aSavedStateFile,
11724 vrc);
11725
11726 mSSData->strStateFilePath = stateFilePathFull;
11727
11728 /* The below setMachineState() will detect the state transition and will
11729 * update the settings file */
11730
11731 return setMachineState(MachineState_Saved);
11732}
11733
11734STDMETHODIMP SessionMachine::PullGuestProperties(ComSafeArrayOut(BSTR, aNames),
11735 ComSafeArrayOut(BSTR, aValues),
11736 ComSafeArrayOut(LONG64, aTimestamps),
11737 ComSafeArrayOut(BSTR, aFlags))
11738{
11739 LogFlowThisFunc(("\n"));
11740
11741#ifdef VBOX_WITH_GUEST_PROPS
11742 using namespace guestProp;
11743
11744 AutoCaller autoCaller(this);
11745 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
11746
11747 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
11748
11749 AssertReturn(!ComSafeArrayOutIsNull(aNames), E_POINTER);
11750 AssertReturn(!ComSafeArrayOutIsNull(aValues), E_POINTER);
11751 AssertReturn(!ComSafeArrayOutIsNull(aTimestamps), E_POINTER);
11752 AssertReturn(!ComSafeArrayOutIsNull(aFlags), E_POINTER);
11753
11754 size_t cEntries = mHWData->mGuestProperties.size();
11755 com::SafeArray<BSTR> names(cEntries);
11756 com::SafeArray<BSTR> values(cEntries);
11757 com::SafeArray<LONG64> timestamps(cEntries);
11758 com::SafeArray<BSTR> flags(cEntries);
11759 unsigned i = 0;
11760 for (HWData::GuestPropertyList::iterator it = mHWData->mGuestProperties.begin();
11761 it != mHWData->mGuestProperties.end();
11762 ++it)
11763 {
11764 char szFlags[MAX_FLAGS_LEN + 1];
11765 it->strName.cloneTo(&names[i]);
11766 it->strValue.cloneTo(&values[i]);
11767 timestamps[i] = it->mTimestamp;
11768 /* If it is NULL, keep it NULL. */
11769 if (it->mFlags)
11770 {
11771 writeFlags(it->mFlags, szFlags);
11772 Bstr(szFlags).cloneTo(&flags[i]);
11773 }
11774 else
11775 flags[i] = NULL;
11776 ++i;
11777 }
11778 names.detachTo(ComSafeArrayOutArg(aNames));
11779 values.detachTo(ComSafeArrayOutArg(aValues));
11780 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
11781 flags.detachTo(ComSafeArrayOutArg(aFlags));
11782 return S_OK;
11783#else
11784 ReturnComNotImplemented();
11785#endif
11786}
11787
11788STDMETHODIMP SessionMachine::PushGuestProperty(IN_BSTR aName,
11789 IN_BSTR aValue,
11790 LONG64 aTimestamp,
11791 IN_BSTR aFlags)
11792{
11793 LogFlowThisFunc(("\n"));
11794
11795#ifdef VBOX_WITH_GUEST_PROPS
11796 using namespace guestProp;
11797
11798 CheckComArgStrNotEmptyOrNull(aName);
11799 CheckComArgMaybeNull(aValue);
11800 CheckComArgMaybeNull(aFlags);
11801
11802 try
11803 {
11804 /*
11805 * Convert input up front.
11806 */
11807 Utf8Str utf8Name(aName);
11808 uint32_t fFlags = NILFLAG;
11809 if (aFlags)
11810 {
11811 Utf8Str utf8Flags(aFlags);
11812 int vrc = validateFlags(utf8Flags.c_str(), &fFlags);
11813 AssertRCReturn(vrc, E_INVALIDARG);
11814 }
11815
11816 /*
11817 * Now grab the object lock, validate the state and do the update.
11818 */
11819 AutoCaller autoCaller(this);
11820 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11821
11822 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11823
11824 switch (mData->mMachineState)
11825 {
11826 case MachineState_Paused:
11827 case MachineState_Running:
11828 case MachineState_Teleporting:
11829 case MachineState_TeleportingPausedVM:
11830 case MachineState_LiveSnapshotting:
11831 case MachineState_DeletingSnapshotOnline:
11832 case MachineState_DeletingSnapshotPaused:
11833 case MachineState_Saving:
11834 break;
11835
11836 default:
11837#ifndef DEBUG_sunlover
11838 AssertMsgFailedReturn(("%s\n", Global::stringifyMachineState(mData->mMachineState)),
11839 VBOX_E_INVALID_VM_STATE);
11840#else
11841 return VBOX_E_INVALID_VM_STATE;
11842#endif
11843 }
11844
11845 setModified(IsModified_MachineData);
11846 mHWData.backup();
11847
11848 /** @todo r=bird: The careful memory handling doesn't work out here because
11849 * the catch block won't undo any damage we've done. So, if push_back throws
11850 * bad_alloc then you've lost the value.
11851 *
11852 * Another thing. Doing a linear search here isn't extremely efficient, esp.
11853 * since values that changes actually bubbles to the end of the list. Using
11854 * something that has an efficient lookup and can tolerate a bit of updates
11855 * would be nice. RTStrSpace is one suggestion (it's not perfect). Some
11856 * combination of RTStrCache (for sharing names and getting uniqueness into
11857 * the bargain) and hash/tree is another. */
11858 for (HWData::GuestPropertyList::iterator iter = mHWData->mGuestProperties.begin();
11859 iter != mHWData->mGuestProperties.end();
11860 ++iter)
11861 if (utf8Name == iter->strName)
11862 {
11863 mHWData->mGuestProperties.erase(iter);
11864 mData->mGuestPropertiesModified = TRUE;
11865 break;
11866 }
11867 if (aValue != NULL)
11868 {
11869 HWData::GuestProperty property = { aName, aValue, aTimestamp, fFlags };
11870 mHWData->mGuestProperties.push_back(property);
11871 mData->mGuestPropertiesModified = TRUE;
11872 }
11873
11874 /*
11875 * Send a callback notification if appropriate
11876 */
11877 if ( mHWData->mGuestPropertyNotificationPatterns.isEmpty()
11878 || RTStrSimplePatternMultiMatch(mHWData->mGuestPropertyNotificationPatterns.c_str(),
11879 RTSTR_MAX,
11880 utf8Name.c_str(),
11881 RTSTR_MAX, NULL)
11882 )
11883 {
11884 alock.leave();
11885
11886 mParent->onGuestPropertyChange(mData->mUuid,
11887 aName,
11888 aValue,
11889 aFlags);
11890 }
11891 }
11892 catch (...)
11893 {
11894 return VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
11895 }
11896 return S_OK;
11897#else
11898 ReturnComNotImplemented();
11899#endif
11900}
11901
11902STDMETHODIMP SessionMachine::EjectMedium(IMediumAttachment *aAttachment,
11903 IMediumAttachment **aNewAttachment)
11904{
11905 CheckComArgNotNull(aAttachment);
11906 CheckComArgOutPointerValid(aNewAttachment);
11907
11908 AutoCaller autoCaller(this);
11909 if (FAILED(autoCaller.rc())) return autoCaller.rc();
11910
11911 // request the host lock first, since might be calling Host methods for getting host drives;
11912 // next, protect the media tree all the while we're in here, as well as our member variables
11913 AutoMultiWriteLock3 multiLock(mParent->host()->lockHandle(),
11914 this->lockHandle(),
11915 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
11916
11917 ComObjPtr<MediumAttachment> pAttach = static_cast<MediumAttachment *>(aAttachment);
11918
11919 Bstr ctrlName;
11920 LONG lPort;
11921 LONG lDevice;
11922 bool fTempEject;
11923 {
11924 AutoCaller autoAttachCaller(this);
11925 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
11926
11927 AutoReadLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11928
11929 /* Need to query the details first, as the IMediumAttachment reference
11930 * might be to the original settings, which we are going to change. */
11931 ctrlName = pAttach->getControllerName();
11932 lPort = pAttach->getPort();
11933 lDevice = pAttach->getDevice();
11934 fTempEject = pAttach->getTempEject();
11935 }
11936
11937 if (!fTempEject)
11938 {
11939 /* Remember previously mounted medium. The medium before taking the
11940 * backup is not necessarily the same thing. */
11941 ComObjPtr<Medium> oldmedium;
11942 oldmedium = pAttach->getMedium();
11943
11944 setModified(IsModified_Storage);
11945 mMediaData.backup();
11946
11947 // The backup operation makes the pAttach reference point to the
11948 // old settings. Re-get the correct reference.
11949 pAttach = findAttachment(mMediaData->mAttachments,
11950 ctrlName.raw(),
11951 lPort,
11952 lDevice);
11953
11954 {
11955 AutoCaller autoAttachCaller(this);
11956 if (FAILED(autoAttachCaller.rc())) return autoAttachCaller.rc();
11957
11958 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11959 if (!oldmedium.isNull())
11960 oldmedium->removeBackReference(mData->mUuid);
11961
11962 pAttach->updateMedium(NULL);
11963 pAttach->updateEjected();
11964 }
11965
11966 setModified(IsModified_Storage);
11967 }
11968 else
11969 {
11970 {
11971 AutoWriteLock attLock(pAttach COMMA_LOCKVAL_SRC_POS);
11972 pAttach->updateEjected();
11973 }
11974 }
11975
11976 pAttach.queryInterfaceTo(aNewAttachment);
11977
11978 return S_OK;
11979}
11980
11981// public methods only for internal purposes
11982/////////////////////////////////////////////////////////////////////////////
11983
11984/**
11985 * Called from the client watcher thread to check for expected or unexpected
11986 * death of the client process that has a direct session to this machine.
11987 *
11988 * On Win32 and on OS/2, this method is called only when we've got the
11989 * mutex (i.e. the client has either died or terminated normally) so it always
11990 * returns @c true (the client is terminated, the session machine is
11991 * uninitialized).
11992 *
11993 * On other platforms, the method returns @c true if the client process has
11994 * terminated normally or abnormally and the session machine was uninitialized,
11995 * and @c false if the client process is still alive.
11996 *
11997 * @note Locks this object for writing.
11998 */
11999bool SessionMachine::checkForDeath()
12000{
12001 Uninit::Reason reason;
12002 bool terminated = false;
12003
12004 /* Enclose autoCaller with a block because calling uninit() from under it
12005 * will deadlock. */
12006 {
12007 AutoCaller autoCaller(this);
12008 if (!autoCaller.isOk())
12009 {
12010 /* return true if not ready, to cause the client watcher to exclude
12011 * the corresponding session from watching */
12012 LogFlowThisFunc(("Already uninitialized!\n"));
12013 return true;
12014 }
12015
12016 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12017
12018 /* Determine the reason of death: if the session state is Closing here,
12019 * everything is fine. Otherwise it means that the client did not call
12020 * OnSessionEnd() before it released the IPC semaphore. This may happen
12021 * either because the client process has abnormally terminated, or
12022 * because it simply forgot to call ISession::Close() before exiting. We
12023 * threat the latter also as an abnormal termination (see
12024 * Session::uninit() for details). */
12025 reason = mData->mSession.mState == SessionState_Unlocking ?
12026 Uninit::Normal :
12027 Uninit::Abnormal;
12028
12029#if defined(RT_OS_WINDOWS)
12030
12031 AssertMsg(mIPCSem, ("semaphore must be created"));
12032
12033 /* release the IPC mutex */
12034 ::ReleaseMutex(mIPCSem);
12035
12036 terminated = true;
12037
12038#elif defined(RT_OS_OS2)
12039
12040 AssertMsg(mIPCSem, ("semaphore must be created"));
12041
12042 /* release the IPC mutex */
12043 ::DosReleaseMutexSem(mIPCSem);
12044
12045 terminated = true;
12046
12047#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
12048
12049 AssertMsg(mIPCSem >= 0, ("semaphore must be created"));
12050
12051 int val = ::semctl(mIPCSem, 0, GETVAL);
12052 if (val > 0)
12053 {
12054 /* the semaphore is signaled, meaning the session is terminated */
12055 terminated = true;
12056 }
12057
12058#else
12059# error "Port me!"
12060#endif
12061
12062 } /* AutoCaller block */
12063
12064 if (terminated)
12065 uninit(reason);
12066
12067 return terminated;
12068}
12069
12070/**
12071 * @note Locks this object for reading.
12072 */
12073HRESULT SessionMachine::onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter)
12074{
12075 LogFlowThisFunc(("\n"));
12076
12077 AutoCaller autoCaller(this);
12078 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12079
12080 ComPtr<IInternalSessionControl> directControl;
12081 {
12082 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12083 directControl = mData->mSession.mDirectControl;
12084 }
12085
12086 /* ignore notifications sent after #OnSessionEnd() is called */
12087 if (!directControl)
12088 return S_OK;
12089
12090 return directControl->OnNetworkAdapterChange(networkAdapter, changeAdapter);
12091}
12092
12093/**
12094 * @note Locks this object for reading.
12095 */
12096HRESULT SessionMachine::onNATRedirectRuleChange(ULONG ulSlot, BOOL aNatRuleRemove, IN_BSTR aRuleName,
12097 NATProtocol_T aProto, IN_BSTR aHostIp, LONG aHostPort, IN_BSTR aGuestIp, LONG aGuestPort)
12098{
12099 LogFlowThisFunc(("\n"));
12100
12101 AutoCaller autoCaller(this);
12102 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12103
12104 ComPtr<IInternalSessionControl> directControl;
12105 {
12106 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12107 directControl = mData->mSession.mDirectControl;
12108 }
12109
12110 /* ignore notifications sent after #OnSessionEnd() is called */
12111 if (!directControl)
12112 return S_OK;
12113 /*
12114 * instead acting like callback we ask IVirtualBox deliver corresponding event
12115 */
12116
12117 mParent->onNatRedirectChange(getId(), ulSlot, RT_BOOL(aNatRuleRemove), aRuleName, aProto, aHostIp, aHostPort, aGuestIp, aGuestPort);
12118 return S_OK;
12119}
12120
12121/**
12122 * @note Locks this object for reading.
12123 */
12124HRESULT SessionMachine::onSerialPortChange(ISerialPort *serialPort)
12125{
12126 LogFlowThisFunc(("\n"));
12127
12128 AutoCaller autoCaller(this);
12129 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12130
12131 ComPtr<IInternalSessionControl> directControl;
12132 {
12133 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12134 directControl = mData->mSession.mDirectControl;
12135 }
12136
12137 /* ignore notifications sent after #OnSessionEnd() is called */
12138 if (!directControl)
12139 return S_OK;
12140
12141 return directControl->OnSerialPortChange(serialPort);
12142}
12143
12144/**
12145 * @note Locks this object for reading.
12146 */
12147HRESULT SessionMachine::onParallelPortChange(IParallelPort *parallelPort)
12148{
12149 LogFlowThisFunc(("\n"));
12150
12151 AutoCaller autoCaller(this);
12152 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12153
12154 ComPtr<IInternalSessionControl> directControl;
12155 {
12156 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12157 directControl = mData->mSession.mDirectControl;
12158 }
12159
12160 /* ignore notifications sent after #OnSessionEnd() is called */
12161 if (!directControl)
12162 return S_OK;
12163
12164 return directControl->OnParallelPortChange(parallelPort);
12165}
12166
12167/**
12168 * @note Locks this object for reading.
12169 */
12170HRESULT SessionMachine::onStorageControllerChange()
12171{
12172 LogFlowThisFunc(("\n"));
12173
12174 AutoCaller autoCaller(this);
12175 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12176
12177 ComPtr<IInternalSessionControl> directControl;
12178 {
12179 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12180 directControl = mData->mSession.mDirectControl;
12181 }
12182
12183 /* ignore notifications sent after #OnSessionEnd() is called */
12184 if (!directControl)
12185 return S_OK;
12186
12187 return directControl->OnStorageControllerChange();
12188}
12189
12190/**
12191 * @note Locks this object for reading.
12192 */
12193HRESULT SessionMachine::onMediumChange(IMediumAttachment *aAttachment, BOOL aForce)
12194{
12195 LogFlowThisFunc(("\n"));
12196
12197 AutoCaller autoCaller(this);
12198 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12199
12200 ComPtr<IInternalSessionControl> directControl;
12201 {
12202 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12203 directControl = mData->mSession.mDirectControl;
12204 }
12205
12206 /* ignore notifications sent after #OnSessionEnd() is called */
12207 if (!directControl)
12208 return S_OK;
12209
12210 return directControl->OnMediumChange(aAttachment, aForce);
12211}
12212
12213/**
12214 * @note Locks this object for reading.
12215 */
12216HRESULT SessionMachine::onCPUChange(ULONG aCPU, BOOL aRemove)
12217{
12218 LogFlowThisFunc(("\n"));
12219
12220 AutoCaller autoCaller(this);
12221 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12222
12223 ComPtr<IInternalSessionControl> directControl;
12224 {
12225 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12226 directControl = mData->mSession.mDirectControl;
12227 }
12228
12229 /* ignore notifications sent after #OnSessionEnd() is called */
12230 if (!directControl)
12231 return S_OK;
12232
12233 return directControl->OnCPUChange(aCPU, aRemove);
12234}
12235
12236HRESULT SessionMachine::onCPUExecutionCapChange(ULONG aExecutionCap)
12237{
12238 LogFlowThisFunc(("\n"));
12239
12240 AutoCaller autoCaller(this);
12241 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12242
12243 ComPtr<IInternalSessionControl> directControl;
12244 {
12245 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12246 directControl = mData->mSession.mDirectControl;
12247 }
12248
12249 /* ignore notifications sent after #OnSessionEnd() is called */
12250 if (!directControl)
12251 return S_OK;
12252
12253 return directControl->OnCPUExecutionCapChange(aExecutionCap);
12254}
12255
12256/**
12257 * @note Locks this object for reading.
12258 */
12259HRESULT SessionMachine::onVRDEServerChange(BOOL aRestart)
12260{
12261 LogFlowThisFunc(("\n"));
12262
12263 AutoCaller autoCaller(this);
12264 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12265
12266 ComPtr<IInternalSessionControl> directControl;
12267 {
12268 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12269 directControl = mData->mSession.mDirectControl;
12270 }
12271
12272 /* ignore notifications sent after #OnSessionEnd() is called */
12273 if (!directControl)
12274 return S_OK;
12275
12276 return directControl->OnVRDEServerChange(aRestart);
12277}
12278
12279/**
12280 * @note Locks this object for reading.
12281 */
12282HRESULT SessionMachine::onUSBControllerChange()
12283{
12284 LogFlowThisFunc(("\n"));
12285
12286 AutoCaller autoCaller(this);
12287 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12288
12289 ComPtr<IInternalSessionControl> directControl;
12290 {
12291 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12292 directControl = mData->mSession.mDirectControl;
12293 }
12294
12295 /* ignore notifications sent after #OnSessionEnd() is called */
12296 if (!directControl)
12297 return S_OK;
12298
12299 return directControl->OnUSBControllerChange();
12300}
12301
12302/**
12303 * @note Locks this object for reading.
12304 */
12305HRESULT SessionMachine::onSharedFolderChange()
12306{
12307 LogFlowThisFunc(("\n"));
12308
12309 AutoCaller autoCaller(this);
12310 AssertComRCReturnRC(autoCaller.rc());
12311
12312 ComPtr<IInternalSessionControl> directControl;
12313 {
12314 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12315 directControl = mData->mSession.mDirectControl;
12316 }
12317
12318 /* ignore notifications sent after #OnSessionEnd() is called */
12319 if (!directControl)
12320 return S_OK;
12321
12322 return directControl->OnSharedFolderChange(FALSE /* aGlobal */);
12323}
12324
12325/**
12326 * @note Locks this object for reading.
12327 */
12328HRESULT SessionMachine::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
12329{
12330 LogFlowThisFunc(("\n"));
12331
12332 AutoCaller autoCaller(this);
12333 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
12334
12335 ComPtr<IInternalSessionControl> directControl;
12336 {
12337 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12338 directControl = mData->mSession.mDirectControl;
12339 }
12340
12341 /* ignore notifications sent after #OnSessionEnd() is called */
12342 if (!directControl)
12343 return S_OK;
12344
12345 return directControl->OnBandwidthGroupChange(aBandwidthGroup);
12346}
12347
12348/**
12349 * @note Locks this object for reading.
12350 */
12351HRESULT SessionMachine::onStorageDeviceChange(IMediumAttachment *aAttachment, BOOL aRemove)
12352{
12353 LogFlowThisFunc(("\n"));
12354
12355 AutoCaller autoCaller(this);
12356 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12357
12358 ComPtr<IInternalSessionControl> directControl;
12359 {
12360 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12361 directControl = mData->mSession.mDirectControl;
12362 }
12363
12364 /* ignore notifications sent after #OnSessionEnd() is called */
12365 if (!directControl)
12366 return S_OK;
12367
12368 return directControl->OnStorageDeviceChange(aAttachment, aRemove);
12369}
12370
12371/**
12372 * Returns @c true if this machine's USB controller reports it has a matching
12373 * filter for the given USB device and @c false otherwise.
12374 *
12375 * @note Caller must have requested machine read lock.
12376 */
12377bool SessionMachine::hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs)
12378{
12379 AutoCaller autoCaller(this);
12380 /* silently return if not ready -- this method may be called after the
12381 * direct machine session has been called */
12382 if (!autoCaller.isOk())
12383 return false;
12384
12385
12386#ifdef VBOX_WITH_USB
12387 switch (mData->mMachineState)
12388 {
12389 case MachineState_Starting:
12390 case MachineState_Restoring:
12391 case MachineState_TeleportingIn:
12392 case MachineState_Paused:
12393 case MachineState_Running:
12394 /** @todo Live Migration: snapshoting & teleporting. Need to fend things of
12395 * elsewhere... */
12396 return mUSBController->hasMatchingFilter(aDevice, aMaskedIfs);
12397 default: break;
12398 }
12399#else
12400 NOREF(aDevice);
12401 NOREF(aMaskedIfs);
12402#endif
12403 return false;
12404}
12405
12406/**
12407 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12408 */
12409HRESULT SessionMachine::onUSBDeviceAttach(IUSBDevice *aDevice,
12410 IVirtualBoxErrorInfo *aError,
12411 ULONG aMaskedIfs)
12412{
12413 LogFlowThisFunc(("\n"));
12414
12415 AutoCaller autoCaller(this);
12416
12417 /* This notification may happen after the machine object has been
12418 * uninitialized (the session was closed), so don't assert. */
12419 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12420
12421 ComPtr<IInternalSessionControl> directControl;
12422 {
12423 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12424 directControl = mData->mSession.mDirectControl;
12425 }
12426
12427 /* fail on notifications sent after #OnSessionEnd() is called, it is
12428 * expected by the caller */
12429 if (!directControl)
12430 return E_FAIL;
12431
12432 /* No locks should be held at this point. */
12433 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12434 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12435
12436 return directControl->OnUSBDeviceAttach(aDevice, aError, aMaskedIfs);
12437}
12438
12439/**
12440 * @note The calls shall hold no locks. Will temporarily lock this object for reading.
12441 */
12442HRESULT SessionMachine::onUSBDeviceDetach(IN_BSTR aId,
12443 IVirtualBoxErrorInfo *aError)
12444{
12445 LogFlowThisFunc(("\n"));
12446
12447 AutoCaller autoCaller(this);
12448
12449 /* This notification may happen after the machine object has been
12450 * uninitialized (the session was closed), so don't assert. */
12451 if (FAILED(autoCaller.rc())) return autoCaller.rc();
12452
12453 ComPtr<IInternalSessionControl> directControl;
12454 {
12455 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12456 directControl = mData->mSession.mDirectControl;
12457 }
12458
12459 /* fail on notifications sent after #OnSessionEnd() is called, it is
12460 * expected by the caller */
12461 if (!directControl)
12462 return E_FAIL;
12463
12464 /* No locks should be held at this point. */
12465 AssertMsg(RTLockValidatorWriteLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorWriteLockGetCount(RTThreadSelf())));
12466 AssertMsg(RTLockValidatorReadLockGetCount(RTThreadSelf()) == 0, ("%d\n", RTLockValidatorReadLockGetCount(RTThreadSelf())));
12467
12468 return directControl->OnUSBDeviceDetach(aId, aError);
12469}
12470
12471// protected methods
12472/////////////////////////////////////////////////////////////////////////////
12473
12474/**
12475 * Helper method to finalize saving the state.
12476 *
12477 * @note Must be called from under this object's lock.
12478 *
12479 * @param aRc S_OK if the snapshot has been taken successfully
12480 * @param aErrMsg human readable error message for failure
12481 *
12482 * @note Locks mParent + this objects for writing.
12483 */
12484HRESULT SessionMachine::endSavingState(HRESULT aRc, const Utf8Str &aErrMsg)
12485{
12486 LogFlowThisFuncEnter();
12487
12488 AutoCaller autoCaller(this);
12489 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12490
12491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12492
12493 HRESULT rc = S_OK;
12494
12495 if (SUCCEEDED(aRc))
12496 {
12497 mSSData->strStateFilePath = mConsoleTaskData.strStateFilePath;
12498
12499 /* save all VM settings */
12500 rc = saveSettings(NULL);
12501 // no need to check whether VirtualBox.xml needs saving also since
12502 // we can't have a name change pending at this point
12503 }
12504 else
12505 {
12506 // delete the saved state file (it might have been already created);
12507 // we need not check whether this is shared with a snapshot here because
12508 // we certainly created this saved state file here anew
12509 RTFileDelete(mConsoleTaskData.strStateFilePath.c_str());
12510 }
12511
12512 /* notify the progress object about operation completion */
12513 Assert(mConsoleTaskData.mProgress);
12514 if (SUCCEEDED(aRc))
12515 mConsoleTaskData.mProgress->notifyComplete(S_OK);
12516 else
12517 {
12518 if (aErrMsg.length())
12519 mConsoleTaskData.mProgress->notifyComplete(aRc,
12520 COM_IIDOF(ISession),
12521 getComponentName(),
12522 aErrMsg.c_str());
12523 else
12524 mConsoleTaskData.mProgress->notifyComplete(aRc);
12525 }
12526
12527 /* clear out the temporary saved state data */
12528 mConsoleTaskData.mLastState = MachineState_Null;
12529 mConsoleTaskData.strStateFilePath.setNull();
12530 mConsoleTaskData.mProgress.setNull();
12531
12532 LogFlowThisFuncLeave();
12533 return rc;
12534}
12535
12536/**
12537 * Deletes the given file if it is no longer in use by either the current machine state
12538 * (if the machine is "saved") or any of the machine's snapshots.
12539 *
12540 * Note: This checks mSSData->strStateFilePath, which is shared by the Machine and SessionMachine
12541 * but is different for each SnapshotMachine. When calling this, the order of calling this
12542 * function on the one hand and changing that variable OR the snapshots tree on the other hand
12543 * is therefore critical. I know, it's all rather messy.
12544 *
12545 * @param strStateFile
12546 * @param pSnapshotToIgnore Passed to Snapshot::sharesSavedStateFile(); this snapshot is ignored in the test for whether the saved state file is in use.
12547 */
12548void SessionMachine::releaseSavedStateFile(const Utf8Str &strStateFile,
12549 Snapshot *pSnapshotToIgnore)
12550{
12551 // it is safe to delete this saved state file if it is not currently in use by the machine ...
12552 if ( (strStateFile.isNotEmpty())
12553 && (strStateFile != mSSData->strStateFilePath) // session machine's saved state
12554 )
12555 // ... and it must also not be shared with other snapshots
12556 if ( !mData->mFirstSnapshot
12557 || !mData->mFirstSnapshot->sharesSavedStateFile(strStateFile, pSnapshotToIgnore)
12558 // this checks the SnapshotMachine's state file paths
12559 )
12560 RTFileDelete(strStateFile.c_str());
12561}
12562
12563/**
12564 * Locks the attached media.
12565 *
12566 * All attached hard disks are locked for writing and DVD/floppy are locked for
12567 * reading. Parents of attached hard disks (if any) are locked for reading.
12568 *
12569 * This method also performs accessibility check of all media it locks: if some
12570 * media is inaccessible, the method will return a failure and a bunch of
12571 * extended error info objects per each inaccessible medium.
12572 *
12573 * Note that this method is atomic: if it returns a success, all media are
12574 * locked as described above; on failure no media is locked at all (all
12575 * succeeded individual locks will be undone).
12576 *
12577 * This method is intended to be called when the machine is in Starting or
12578 * Restoring state and asserts otherwise.
12579 *
12580 * The locks made by this method must be undone by calling #unlockMedia() when
12581 * no more needed.
12582 */
12583HRESULT SessionMachine::lockMedia()
12584{
12585 AutoCaller autoCaller(this);
12586 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12587
12588 AutoMultiWriteLock2 alock(this->lockHandle(),
12589 &mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
12590
12591 AssertReturn( mData->mMachineState == MachineState_Starting
12592 || mData->mMachineState == MachineState_Restoring
12593 || mData->mMachineState == MachineState_TeleportingIn, E_FAIL);
12594 /* bail out if trying to lock things with already set up locking */
12595 AssertReturn(mData->mSession.mLockedMedia.IsEmpty(), E_FAIL);
12596
12597 clearError();
12598 MultiResult mrc(S_OK);
12599
12600 /* Collect locking information for all medium objects attached to the VM. */
12601 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
12602 it != mMediaData->mAttachments.end();
12603 ++it)
12604 {
12605 MediumAttachment* pAtt = *it;
12606 DeviceType_T devType = pAtt->getType();
12607 Medium *pMedium = pAtt->getMedium();
12608
12609 MediumLockList *pMediumLockList(new MediumLockList());
12610 // There can be attachments without a medium (floppy/dvd), and thus
12611 // it's impossible to create a medium lock list. It still makes sense
12612 // to have the empty medium lock list in the map in case a medium is
12613 // attached later.
12614 if (pMedium != NULL)
12615 {
12616 MediumType_T mediumType = pMedium->getType();
12617 bool fIsReadOnlyLock = mediumType == MediumType_Readonly
12618 || mediumType == MediumType_Shareable;
12619 bool fIsVitalImage = (devType == DeviceType_HardDisk);
12620
12621 mrc = pMedium->createMediumLockList(fIsVitalImage /* fFailIfInaccessible */,
12622 !fIsReadOnlyLock /* fMediumLockWrite */,
12623 NULL,
12624 *pMediumLockList);
12625 if (FAILED(mrc))
12626 {
12627 delete pMediumLockList;
12628 mData->mSession.mLockedMedia.Clear();
12629 break;
12630 }
12631 }
12632
12633 HRESULT rc = mData->mSession.mLockedMedia.Insert(pAtt, pMediumLockList);
12634 if (FAILED(rc))
12635 {
12636 mData->mSession.mLockedMedia.Clear();
12637 mrc = setError(rc,
12638 tr("Collecting locking information for all attached media failed"));
12639 break;
12640 }
12641 }
12642
12643 if (SUCCEEDED(mrc))
12644 {
12645 /* Now lock all media. If this fails, nothing is locked. */
12646 HRESULT rc = mData->mSession.mLockedMedia.Lock();
12647 if (FAILED(rc))
12648 {
12649 mrc = setError(rc,
12650 tr("Locking of attached media failed"));
12651 }
12652 }
12653
12654 return mrc;
12655}
12656
12657/**
12658 * Undoes the locks made by by #lockMedia().
12659 */
12660void SessionMachine::unlockMedia()
12661{
12662 AutoCaller autoCaller(this);
12663 AssertComRCReturnVoid(autoCaller.rc());
12664
12665 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12666
12667 /* we may be holding important error info on the current thread;
12668 * preserve it */
12669 ErrorInfoKeeper eik;
12670
12671 HRESULT rc = mData->mSession.mLockedMedia.Clear();
12672 AssertComRC(rc);
12673}
12674
12675/**
12676 * Helper to change the machine state (reimplementation).
12677 *
12678 * @note Locks this object for writing.
12679 */
12680HRESULT SessionMachine::setMachineState(MachineState_T aMachineState)
12681{
12682 LogFlowThisFuncEnter();
12683 LogFlowThisFunc(("aMachineState=%s\n", Global::stringifyMachineState(aMachineState) ));
12684
12685 AutoCaller autoCaller(this);
12686 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12687
12688 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
12689
12690 MachineState_T oldMachineState = mData->mMachineState;
12691
12692 AssertMsgReturn(oldMachineState != aMachineState,
12693 ("oldMachineState=%s, aMachineState=%s\n",
12694 Global::stringifyMachineState(oldMachineState), Global::stringifyMachineState(aMachineState)),
12695 E_FAIL);
12696
12697 HRESULT rc = S_OK;
12698
12699 int stsFlags = 0;
12700 bool deleteSavedState = false;
12701
12702 /* detect some state transitions */
12703
12704 if ( ( oldMachineState == MachineState_Saved
12705 && aMachineState == MachineState_Restoring)
12706 || ( ( oldMachineState == MachineState_PoweredOff
12707 || oldMachineState == MachineState_Teleported
12708 || oldMachineState == MachineState_Aborted
12709 )
12710 && ( aMachineState == MachineState_TeleportingIn
12711 || aMachineState == MachineState_Starting
12712 )
12713 )
12714 )
12715 {
12716 /* The EMT thread is about to start */
12717
12718 /* Nothing to do here for now... */
12719
12720 /// @todo NEWMEDIA don't let mDVDDrive and other children
12721 /// change anything when in the Starting/Restoring state
12722 }
12723 else if ( ( oldMachineState == MachineState_Running
12724 || oldMachineState == MachineState_Paused
12725 || oldMachineState == MachineState_Teleporting
12726 || oldMachineState == MachineState_LiveSnapshotting
12727 || oldMachineState == MachineState_Stuck
12728 || oldMachineState == MachineState_Starting
12729 || oldMachineState == MachineState_Stopping
12730 || oldMachineState == MachineState_Saving
12731 || oldMachineState == MachineState_Restoring
12732 || oldMachineState == MachineState_TeleportingPausedVM
12733 || oldMachineState == MachineState_TeleportingIn
12734 )
12735 && ( aMachineState == MachineState_PoweredOff
12736 || aMachineState == MachineState_Saved
12737 || aMachineState == MachineState_Teleported
12738 || aMachineState == MachineState_Aborted
12739 )
12740 /* ignore PoweredOff->Saving->PoweredOff transition when taking a
12741 * snapshot */
12742 && ( mConsoleTaskData.mSnapshot.isNull()
12743 || mConsoleTaskData.mLastState >= MachineState_Running /** @todo Live Migration: clean up (lazy bird) */
12744 )
12745 )
12746 {
12747 /* The EMT thread has just stopped, unlock attached media. Note that as
12748 * opposed to locking that is done from Console, we do unlocking here
12749 * because the VM process may have aborted before having a chance to
12750 * properly unlock all media it locked. */
12751
12752 unlockMedia();
12753 }
12754
12755 if (oldMachineState == MachineState_Restoring)
12756 {
12757 if (aMachineState != MachineState_Saved)
12758 {
12759 /*
12760 * delete the saved state file once the machine has finished
12761 * restoring from it (note that Console sets the state from
12762 * Restoring to Saved if the VM couldn't restore successfully,
12763 * to give the user an ability to fix an error and retry --
12764 * we keep the saved state file in this case)
12765 */
12766 deleteSavedState = true;
12767 }
12768 }
12769 else if ( oldMachineState == MachineState_Saved
12770 && ( aMachineState == MachineState_PoweredOff
12771 || aMachineState == MachineState_Aborted
12772 || aMachineState == MachineState_Teleported
12773 )
12774 )
12775 {
12776 /*
12777 * delete the saved state after Console::ForgetSavedState() is called
12778 * or if the VM process (owning a direct VM session) crashed while the
12779 * VM was Saved
12780 */
12781
12782 /// @todo (dmik)
12783 // Not sure that deleting the saved state file just because of the
12784 // client death before it attempted to restore the VM is a good
12785 // thing. But when it crashes we need to go to the Aborted state
12786 // which cannot have the saved state file associated... The only
12787 // way to fix this is to make the Aborted condition not a VM state
12788 // but a bool flag: i.e., when a crash occurs, set it to true and
12789 // change the state to PoweredOff or Saved depending on the
12790 // saved state presence.
12791
12792 deleteSavedState = true;
12793 mData->mCurrentStateModified = TRUE;
12794 stsFlags |= SaveSTS_CurStateModified;
12795 }
12796
12797 if ( aMachineState == MachineState_Starting
12798 || aMachineState == MachineState_Restoring
12799 || aMachineState == MachineState_TeleportingIn
12800 )
12801 {
12802 /* set the current state modified flag to indicate that the current
12803 * state is no more identical to the state in the
12804 * current snapshot */
12805 if (!mData->mCurrentSnapshot.isNull())
12806 {
12807 mData->mCurrentStateModified = TRUE;
12808 stsFlags |= SaveSTS_CurStateModified;
12809 }
12810 }
12811
12812 if (deleteSavedState)
12813 {
12814 if (mRemoveSavedState)
12815 {
12816 Assert(!mSSData->strStateFilePath.isEmpty());
12817
12818 // it is safe to delete the saved state file if ...
12819 if ( !mData->mFirstSnapshot // ... we have no snapshots or
12820 || !mData->mFirstSnapshot->sharesSavedStateFile(mSSData->strStateFilePath, NULL /* pSnapshotToIgnore */)
12821 // ... none of the snapshots share the saved state file
12822 )
12823 RTFileDelete(mSSData->strStateFilePath.c_str());
12824 }
12825
12826 mSSData->strStateFilePath.setNull();
12827 stsFlags |= SaveSTS_StateFilePath;
12828 }
12829
12830 /* redirect to the underlying peer machine */
12831 mPeer->setMachineState(aMachineState);
12832
12833 if ( aMachineState == MachineState_PoweredOff
12834 || aMachineState == MachineState_Teleported
12835 || aMachineState == MachineState_Aborted
12836 || aMachineState == MachineState_Saved)
12837 {
12838 /* the machine has stopped execution
12839 * (or the saved state file was adopted) */
12840 stsFlags |= SaveSTS_StateTimeStamp;
12841 }
12842
12843 if ( ( oldMachineState == MachineState_PoweredOff
12844 || oldMachineState == MachineState_Aborted
12845 || oldMachineState == MachineState_Teleported
12846 )
12847 && aMachineState == MachineState_Saved)
12848 {
12849 /* the saved state file was adopted */
12850 Assert(!mSSData->strStateFilePath.isEmpty());
12851 stsFlags |= SaveSTS_StateFilePath;
12852 }
12853
12854#ifdef VBOX_WITH_GUEST_PROPS
12855 if ( aMachineState == MachineState_PoweredOff
12856 || aMachineState == MachineState_Aborted
12857 || aMachineState == MachineState_Teleported)
12858 {
12859 /* Make sure any transient guest properties get removed from the
12860 * property store on shutdown. */
12861
12862 HWData::GuestPropertyList::iterator it;
12863 BOOL fNeedsSaving = mData->mGuestPropertiesModified;
12864 if (!fNeedsSaving)
12865 for (it = mHWData->mGuestProperties.begin();
12866 it != mHWData->mGuestProperties.end(); ++it)
12867 if ( (it->mFlags & guestProp::TRANSIENT)
12868 || (it->mFlags & guestProp::TRANSRESET))
12869 {
12870 fNeedsSaving = true;
12871 break;
12872 }
12873 if (fNeedsSaving)
12874 {
12875 mData->mCurrentStateModified = TRUE;
12876 stsFlags |= SaveSTS_CurStateModified;
12877 SaveSettings(); // @todo r=dj why the public method? why first SaveSettings and then saveStateSettings?
12878 }
12879 }
12880#endif
12881
12882 rc = saveStateSettings(stsFlags);
12883
12884 if ( ( oldMachineState != MachineState_PoweredOff
12885 && oldMachineState != MachineState_Aborted
12886 && oldMachineState != MachineState_Teleported
12887 )
12888 && ( aMachineState == MachineState_PoweredOff
12889 || aMachineState == MachineState_Aborted
12890 || aMachineState == MachineState_Teleported
12891 )
12892 )
12893 {
12894 /* we've been shut down for any reason */
12895 /* no special action so far */
12896 }
12897
12898 LogFlowThisFunc(("rc=%Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
12899 LogFlowThisFuncLeave();
12900 return rc;
12901}
12902
12903/**
12904 * Sends the current machine state value to the VM process.
12905 *
12906 * @note Locks this object for reading, then calls a client process.
12907 */
12908HRESULT SessionMachine::updateMachineStateOnClient()
12909{
12910 AutoCaller autoCaller(this);
12911 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
12912
12913 ComPtr<IInternalSessionControl> directControl;
12914 {
12915 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
12916 AssertReturn(!!mData, E_FAIL);
12917 directControl = mData->mSession.mDirectControl;
12918
12919 /* directControl may be already set to NULL here in #OnSessionEnd()
12920 * called too early by the direct session process while there is still
12921 * some operation (like deleting the snapshot) in progress. The client
12922 * process in this case is waiting inside Session::close() for the
12923 * "end session" process object to complete, while #uninit() called by
12924 * #checkForDeath() on the Watcher thread is waiting for the pending
12925 * operation to complete. For now, we accept this inconsistent behavior
12926 * and simply do nothing here. */
12927
12928 if (mData->mSession.mState == SessionState_Unlocking)
12929 return S_OK;
12930
12931 AssertReturn(!directControl.isNull(), E_FAIL);
12932 }
12933
12934 return directControl->UpdateMachineState(mData->mMachineState);
12935}
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