VirtualBox

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

Last change on this file since 39882 was 39821, checked in by vboxsync, 13 years ago

API/GuestProperties: add DeleteGuestProperty.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette