VirtualBox

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

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

Main/Machine: remove leftover debugging hack

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

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