VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/VirtualBoxImpl.cpp@ 35599

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

gcc-4.6 warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 146.1 KB
Line 
1/* $Id: VirtualBoxImpl.cpp 35435 2011-01-07 16:52:31Z vboxsync $ */
2
3/** @file
4 * Implementation of IVirtualBox in VBoxSVC.
5 */
6
7/*
8 * Copyright (C) 2006-2010 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19#include <iprt/asm.h>
20#include <iprt/buildconfig.h>
21#include <iprt/cpp/utils.h>
22#include <iprt/dir.h>
23#include <iprt/env.h>
24#include <iprt/file.h>
25#include <iprt/path.h>
26#include <iprt/process.h>
27#include <iprt/string.h>
28#include <iprt/stream.h>
29#include <iprt/thread.h>
30#include <iprt/uuid.h>
31#include <iprt/cpp/xml.h>
32
33#include <VBox/com/com.h>
34#include <VBox/com/array.h>
35#include "VBox/com/EventQueue.h"
36
37#include <VBox/err.h>
38#include <VBox/param.h>
39#include <VBox/settings.h>
40#include <VBox/version.h>
41
42#include <package-generated.h>
43
44#include <algorithm>
45#include <set>
46#include <vector>
47#include <memory> // for auto_ptr
48
49#include <typeinfo>
50
51#include "VirtualBoxImpl.h"
52
53#include "Global.h"
54#include "MachineImpl.h"
55#include "MediumImpl.h"
56#include "SharedFolderImpl.h"
57#include "ProgressImpl.h"
58#include "ProgressProxyImpl.h"
59#include "HostImpl.h"
60#include "USBControllerImpl.h"
61#include "SystemPropertiesImpl.h"
62#include "GuestOSTypeImpl.h"
63#include "DHCPServerRunner.h"
64#include "DHCPServerImpl.h"
65#ifdef VBOX_WITH_RESOURCE_USAGE_API
66# include "PerformanceImpl.h"
67#endif /* VBOX_WITH_RESOURCE_USAGE_API */
68#include "EventImpl.h"
69#include "VBoxEvents.h"
70#ifdef VBOX_WITH_EXTPACK
71# include "ExtPackManagerImpl.h"
72#endif
73
74#include "AutoCaller.h"
75#include "Logging.h"
76#include "objectslist.h"
77
78#ifdef RT_OS_WINDOWS
79# include "win/svchlp.h"
80# include "win/VBoxComEvents.h"
81#endif
82
83////////////////////////////////////////////////////////////////////////////////
84//
85// Definitions
86//
87////////////////////////////////////////////////////////////////////////////////
88
89#define VBOX_GLOBAL_SETTINGS_FILE "VirtualBox.xml"
90
91////////////////////////////////////////////////////////////////////////////////
92//
93// Global variables
94//
95////////////////////////////////////////////////////////////////////////////////
96
97// static
98Bstr VirtualBox::sVersion;
99
100// static
101ULONG VirtualBox::sRevision;
102
103// static
104Bstr VirtualBox::sPackageType;
105
106////////////////////////////////////////////////////////////////////////////////
107//
108// VirtualBoxCallbackRegistration
109//
110////////////////////////////////////////////////////////////////////////////////
111
112/**
113 * Registered IVirtualBoxCallback, used by VirtualBox::CallbackList and
114 * VirtualBox::Data::llCallbacks.
115 *
116 * In addition to keeping the interface pointer this also keeps track of the
117 * methods that asked to not be called again. The latter is for reducing
118 * unnecessary IPC.
119 */
120class VirtualBoxCallbackRegistration
121{
122public:
123 /** Callback bit indexes (for bmDisabled). */
124 typedef enum
125 {
126 kOnMachineStateChanged = 0,
127 kOnMachineDataChanged,
128 kOnExtraDataCanChange,
129 kOnExtraDataChanged,
130 kOnMediumRegistered,
131 kOnMachineRegistered,
132 kOnSessionStateChanged,
133 kOnSnapshotTaken,
134 kOnSnapshotDeleted,
135 kOnSnapshotChanged,
136 kOnGuestPropertyChanged
137 } CallbackBit;
138
139 VirtualBoxCallbackRegistration()
140 {
141 /* nothing */
142 }
143
144 ~VirtualBoxCallbackRegistration()
145 {
146 /* nothing */
147 }
148};
149
150////////////////////////////////////////////////////////////////////////////////
151//
152// CallbackEvent class
153//
154////////////////////////////////////////////////////////////////////////////////
155
156/**
157 * Abstract callback event class to asynchronously call VirtualBox callbacks
158 * on a dedicated event thread. Subclasses reimplement #handleCallback()
159 * to call appropriate IVirtualBoxCallback methods depending on the event
160 * to be dispatched.
161 *
162 * @note The VirtualBox instance passed to the constructor is strongly
163 * referenced, so that the VirtualBox singleton won't be released until the
164 * event gets handled by the event thread.
165 */
166class VirtualBox::CallbackEvent : public Event
167{
168public:
169
170 CallbackEvent(VirtualBox *aVirtualBox, VirtualBoxCallbackRegistration::CallbackBit aWhat)
171 : mVirtualBox(aVirtualBox), mWhat(aWhat)
172 {
173 Assert(aVirtualBox);
174 }
175
176 void *handler();
177
178 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc) = 0;
179
180private:
181
182 /**
183 * Note that this is a weak ref -- the CallbackEvent handler thread
184 * is bound to the lifetime of the VirtualBox instance, so it's safe.
185 */
186 VirtualBox *mVirtualBox;
187protected:
188 VirtualBoxCallbackRegistration::CallbackBit mWhat;
189};
190
191////////////////////////////////////////////////////////////////////////////////
192//
193// VirtualBox private member data definition
194//
195////////////////////////////////////////////////////////////////////////////////
196
197#if defined(RT_OS_WINDOWS)
198 #define UPDATEREQARG NULL
199 #define UPDATEREQTYPE HANDLE
200#elif defined(RT_OS_OS2)
201 #define UPDATEREQARG NIL_RTSEMEVENT
202 #define UPDATEREQTYPE RTSEMEVENT
203#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
204 #define UPDATEREQARG
205 #define UPDATEREQTYPE RTSEMEVENT
206#else
207# error "Port me!"
208#endif
209
210typedef ObjectsList<Machine> MachinesOList;
211typedef ObjectsList<Medium> MediaOList;
212typedef ObjectsList<GuestOSType> GuestOSTypesOList;
213typedef ObjectsList<SharedFolder> SharedFoldersOList;
214typedef ObjectsList<DHCPServer> DHCPServersOList;
215
216typedef std::map<Guid, ComPtr<IProgress> > ProgressMap;
217typedef std::map<Guid, ComObjPtr<Medium> > HardDiskMap;
218
219/**
220 * Main VirtualBox data structure.
221 * @note |const| members are persistent during lifetime so can be accessed
222 * without locking.
223 */
224struct VirtualBox::Data
225{
226 Data()
227 : pMainConfigFile(NULL),
228 uuidMediaRegistry("48024e5c-fdd9-470f-93af-ec29f7ea518c"),
229 lockMachines(LOCKCLASS_LISTOFMACHINES),
230 allMachines(lockMachines),
231 lockGuestOSTypes(LOCKCLASS_LISTOFOTHEROBJECTS),
232 allGuestOSTypes(lockGuestOSTypes),
233 lockMedia(LOCKCLASS_LISTOFMEDIA),
234 allHardDisks(lockMedia),
235 allDVDImages(lockMedia),
236 allFloppyImages(lockMedia),
237 lockSharedFolders(LOCKCLASS_LISTOFOTHEROBJECTS),
238 allSharedFolders(lockSharedFolders),
239 lockDHCPServers(LOCKCLASS_LISTOFOTHEROBJECTS),
240 allDHCPServers(lockDHCPServers),
241 mtxProgressOperations(LOCKCLASS_PROGRESSLIST),
242 updateReq(UPDATEREQARG),
243 threadClientWatcher(NIL_RTTHREAD),
244 threadAsyncEvent(NIL_RTTHREAD),
245 pAsyncEventQ(NULL)
246 {
247 }
248
249 ~Data()
250 {
251 if (pMainConfigFile)
252 {
253 delete pMainConfigFile;
254 pMainConfigFile = NULL;
255 }
256 };
257
258 // const data members not requiring locking
259 const Utf8Str strHomeDir;
260
261 // VirtualBox main settings file
262 const Utf8Str strSettingsFilePath;
263 settings::MainConfigFile *pMainConfigFile;
264
265 // constant pseudo-machine ID for global media registry
266 const Guid uuidMediaRegistry;
267
268 // const objects not requiring locking
269 const ComObjPtr<Host> pHost;
270 const ComObjPtr<SystemProperties> pSystemProperties;
271#ifdef VBOX_WITH_RESOURCE_USAGE_API
272 const ComObjPtr<PerformanceCollector> pPerformanceCollector;
273#endif /* VBOX_WITH_RESOURCE_USAGE_API */
274
275 // Each of the following lists use a particular lock handle that protects the
276 // list as a whole. As opposed to version 3.1 and earlier, these lists no
277 // longer need the main VirtualBox object lock, but only the respective list
278 // lock. In each case, the locking order is defined that the list must be
279 // requested before object locks of members of the lists (see the order definitions
280 // in AutoLock.h; e.g. LOCKCLASS_LISTOFMACHINES before LOCKCLASS_MACHINEOBJECT).
281 RWLockHandle lockMachines;
282 MachinesOList allMachines;
283
284 RWLockHandle lockGuestOSTypes;
285 GuestOSTypesOList allGuestOSTypes;
286
287 // All the media lists are protected by the following locking handle:
288 RWLockHandle lockMedia;
289 MediaOList allHardDisks, // base images only!
290 allDVDImages,
291 allFloppyImages;
292 // the hard disks map is an additional map sorted by UUID for quick lookup
293 // and contains ALL hard disks (base and differencing); it is protected by
294 // the same lock as the other media lists above
295 HardDiskMap mapHardDisks;
296
297 // list of pending machine renames (also protected by media tree lock;
298 // see VirtualBox::rememberMachineNameChangeForMedia())
299 struct PendingMachineRename
300 {
301 Utf8Str strConfigDirOld;
302 Utf8Str strConfigDirNew;
303 };
304 typedef std::list<PendingMachineRename> PendingMachineRenamesList;
305 PendingMachineRenamesList llPendingMachineRenames;
306
307 RWLockHandle lockSharedFolders;
308 SharedFoldersOList allSharedFolders;
309
310 RWLockHandle lockDHCPServers;
311 DHCPServersOList allDHCPServers;
312
313 RWLockHandle mtxProgressOperations;
314 ProgressMap mapProgressOperations;
315
316 // the following are data for the client watcher thread
317 const UPDATEREQTYPE updateReq;
318 const RTTHREAD threadClientWatcher;
319 typedef std::list<RTPROCESS> ProcessList;
320 ProcessList llProcesses;
321
322 // the following are data for the async event thread
323 const RTTHREAD threadAsyncEvent;
324 EventQueue * const pAsyncEventQ;
325 const ComObjPtr<EventSource> pEventSource;
326
327#ifdef VBOX_WITH_EXTPACK
328 /** The extension pack manager object lives here. */
329 const ComObjPtr<ExtPackManager> ptrExtPackManager;
330#endif
331};
332
333// constructor / destructor
334/////////////////////////////////////////////////////////////////////////////
335
336VirtualBox::VirtualBox()
337{}
338
339VirtualBox::~VirtualBox()
340{}
341
342HRESULT VirtualBox::FinalConstruct()
343{
344 LogFlowThisFunc(("\n"));
345
346 return init();
347}
348
349void VirtualBox::FinalRelease()
350{
351 LogFlowThisFunc(("\n"));
352
353 uninit();
354}
355
356// public initializer/uninitializer for internal purposes only
357/////////////////////////////////////////////////////////////////////////////
358
359/**
360 * Initializes the VirtualBox object.
361 *
362 * @return COM result code
363 */
364HRESULT VirtualBox::init()
365{
366 /* Enclose the state transition NotReady->InInit->Ready */
367 AutoInitSpan autoInitSpan(this);
368 AssertReturn(autoInitSpan.isOk(), E_FAIL);
369
370 /* Locking this object for writing during init sounds a bit paradoxical,
371 * but in the current locking mess this avoids that some code gets a
372 * read lock and later calls code which wants the same write lock. */
373 AutoWriteLock lock(this COMMA_LOCKVAL_SRC_POS);
374
375 // allocate our instance data
376 m = new Data;
377
378 LogFlow(("===========================================================\n"));
379 LogFlowThisFuncEnter();
380
381 if (sVersion.isEmpty())
382 sVersion = VBOX_VERSION_STRING;
383 sRevision = RTBldCfgRevision();
384 if (sPackageType.isEmpty())
385 sPackageType = VBOX_PACKAGE_STRING;
386 LogFlowThisFunc(("Version: %ls, Package: %ls\n", sVersion.raw(), sPackageType.raw()));
387
388 /* Get the VirtualBox home directory. */
389 {
390 char szHomeDir[RTPATH_MAX];
391 int vrc = com::GetVBoxUserHomeDirectory(szHomeDir, sizeof(szHomeDir));
392 if (RT_FAILURE(vrc))
393 return setError(E_FAIL,
394 tr("Could not create the VirtualBox home directory '%s' (%Rrc)"),
395 szHomeDir, vrc);
396
397 unconst(m->strHomeDir) = szHomeDir;
398 }
399
400 /* compose the VirtualBox.xml file name */
401 unconst(m->strSettingsFilePath) = Utf8StrFmt("%s%c%s",
402 m->strHomeDir.c_str(),
403 RTPATH_DELIMITER,
404 VBOX_GLOBAL_SETTINGS_FILE);
405 HRESULT rc = S_OK;
406 bool fCreate = false;
407 try
408 {
409 // load and parse VirtualBox.xml; this will throw on XML or logic errors
410 try
411 {
412 m->pMainConfigFile = new settings::MainConfigFile(&m->strSettingsFilePath);
413 }
414 catch (xml::EIPRTFailure &e)
415 {
416 // this is thrown by the XML backend if the RTOpen() call fails;
417 // only if the main settings file does not exist, create it,
418 // if there's something more serious, then do fail!
419 if (e.rc() == VERR_FILE_NOT_FOUND)
420 fCreate = true;
421 else
422 throw;
423 }
424
425 if (fCreate)
426 m->pMainConfigFile = new settings::MainConfigFile(NULL);
427
428#ifdef VBOX_WITH_RESOURCE_USAGE_API
429 /* create the performance collector object BEFORE host */
430 unconst(m->pPerformanceCollector).createObject();
431 rc = m->pPerformanceCollector->init();
432 ComAssertComRCThrowRC(rc);
433#endif /* VBOX_WITH_RESOURCE_USAGE_API */
434
435 /* create the host object early, machines will need it */
436 unconst(m->pHost).createObject();
437 rc = m->pHost->init(this);
438 ComAssertComRCThrowRC(rc);
439
440 rc = m->pHost->loadSettings(m->pMainConfigFile->host);
441 if (FAILED(rc)) throw rc;
442
443 /* create the system properties object, someone may need it too */
444 unconst(m->pSystemProperties).createObject();
445 rc = m->pSystemProperties->init(this);
446 ComAssertComRCThrowRC(rc);
447
448 rc = m->pSystemProperties->loadSettings(m->pMainConfigFile->systemProperties);
449 if (FAILED(rc)) throw rc;
450
451 /* guest OS type objects, needed by machines */
452 for (size_t i = 0; i < RT_ELEMENTS(Global::sOSTypes); ++i)
453 {
454 ComObjPtr<GuestOSType> guestOSTypeObj;
455 rc = guestOSTypeObj.createObject();
456 if (SUCCEEDED(rc))
457 {
458 rc = guestOSTypeObj->init(Global::sOSTypes[i]);
459 if (SUCCEEDED(rc))
460 m->allGuestOSTypes.addChild(guestOSTypeObj);
461 }
462 ComAssertComRCThrowRC(rc);
463 }
464
465 /* all registered media, needed by machines */
466 if (FAILED(rc = initMedia(m->uuidMediaRegistry,
467 m->pMainConfigFile->mediaRegistry,
468 Utf8Str::Empty))) // const Utf8Str &machineFolder
469 throw rc;
470
471 /* machines */
472 if (FAILED(rc = initMachines()))
473 throw rc;
474
475
476#ifdef DEBUG
477 LogFlowThisFunc(("Dumping media backreferences\n"));
478 dumpAllBackRefs();
479#endif
480
481 /* net services */
482 for (settings::DHCPServersList::const_iterator it = m->pMainConfigFile->llDhcpServers.begin();
483 it != m->pMainConfigFile->llDhcpServers.end();
484 ++it)
485 {
486 const settings::DHCPServer &data = *it;
487
488 ComObjPtr<DHCPServer> pDhcpServer;
489 if (SUCCEEDED(rc = pDhcpServer.createObject()))
490 rc = pDhcpServer->init(this, data);
491 if (FAILED(rc)) throw rc;
492
493 rc = registerDHCPServer(pDhcpServer, false /* aSaveRegistry */);
494 if (FAILED(rc)) throw rc;
495 }
496
497 /* events */
498 if (SUCCEEDED(rc = unconst(m->pEventSource).createObject()))
499 rc = m->pEventSource->init(static_cast<IVirtualBox*>(this));
500 if (FAILED(rc)) throw rc;
501
502#ifdef VBOX_WITH_EXTPACK
503 /* extension manager */
504 rc = unconst(m->ptrExtPackManager).createObject();
505 if (SUCCEEDED(rc))
506 rc = m->ptrExtPackManager->initExtPackManager(this, VBOXEXTPACKCTX_PER_USER_DAEMON);
507 if (FAILED(rc))
508 throw rc;
509#endif
510 }
511 catch (HRESULT err)
512 {
513 /* we assume that error info is set by the thrower */
514 rc = err;
515 }
516 catch (...)
517 {
518 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
519 }
520
521 if (SUCCEEDED(rc))
522 {
523 /* start the client watcher thread */
524#if defined(RT_OS_WINDOWS)
525 unconst(m->updateReq) = ::CreateEvent(NULL, FALSE, FALSE, NULL);
526#elif defined(RT_OS_OS2)
527 RTSemEventCreate(&unconst(m->updateReq));
528#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
529 RTSemEventCreate(&unconst(m->updateReq));
530#else
531# error "Port me!"
532#endif
533 int vrc = RTThreadCreate(&unconst(m->threadClientWatcher),
534 ClientWatcher,
535 (void *)this,
536 0,
537 RTTHREADTYPE_MAIN_WORKER,
538 RTTHREADFLAGS_WAITABLE,
539 "Watcher");
540 ComAssertRC(vrc);
541 if (RT_FAILURE(vrc))
542 rc = E_FAIL;
543 }
544
545 if (SUCCEEDED(rc))
546 {
547 try
548 {
549 /* start the async event handler thread */
550 int vrc = RTThreadCreate(&unconst(m->threadAsyncEvent),
551 AsyncEventHandler,
552 &unconst(m->pAsyncEventQ),
553 0,
554 RTTHREADTYPE_MAIN_WORKER,
555 RTTHREADFLAGS_WAITABLE,
556 "EventHandler");
557 ComAssertRCThrow(vrc, E_FAIL);
558
559 /* wait until the thread sets m->pAsyncEventQ */
560 RTThreadUserWait(m->threadAsyncEvent, RT_INDEFINITE_WAIT);
561 ComAssertThrow(m->pAsyncEventQ, E_FAIL);
562 }
563 catch (HRESULT aRC)
564 {
565 rc = aRC;
566 }
567 }
568
569 /* Confirm a successful initialization when it's the case */
570 if (SUCCEEDED(rc))
571 autoInitSpan.setSucceeded();
572
573#ifdef VBOX_WITH_EXTPACK
574 /* Let the extension packs have a go at things. */
575 if (SUCCEEDED(rc))
576 {
577 lock.release();
578 m->ptrExtPackManager->callAllVirtualBoxReadyHooks();
579 }
580#endif
581
582 LogFlowThisFunc(("rc=%08X\n", rc));
583 LogFlowThisFuncLeave();
584 LogFlow(("===========================================================\n"));
585 return rc;
586}
587
588HRESULT VirtualBox::initMachines()
589{
590 for (settings::MachinesRegistry::const_iterator it = m->pMainConfigFile->llMachines.begin();
591 it != m->pMainConfigFile->llMachines.end();
592 ++it)
593 {
594 HRESULT rc = S_OK;
595 const settings::MachineRegistryEntry &xmlMachine = *it;
596 Guid uuid = xmlMachine.uuid;
597
598 ComObjPtr<Machine> pMachine;
599 if (SUCCEEDED(rc = pMachine.createObject()))
600 {
601 rc = pMachine->init(this,
602 xmlMachine.strSettingsFile,
603 &uuid);
604 if (SUCCEEDED(rc))
605 rc = registerMachine(pMachine);
606 if (FAILED(rc))
607 return rc;
608 }
609 }
610
611 return S_OK;
612}
613
614/**
615 * Loads a media registry from XML and adds the media contained therein to
616 * the global lists of known media.
617 *
618 * This now (4.0) gets called from two locations:
619 *
620 * -- VirtualBox::init(), to load the global media registry from VirtualBox.xml;
621 *
622 * -- Machine::loadMachineDataFromSettings(), to load the per-machine registry
623 * from machine XML, for machines created with VirtualBox 4.0 or later.
624 *
625 * In both cases, the media found are added to the global lists so the
626 * global arrays of media (including the GUI's virtual media manager)
627 * continue to work as before.
628 *
629 * @param uuidMachineRegistry The UUID of the media registry. This is either the
630 * transient UUID created at VirtualBox startup for the global registry or
631 * a machine ID.
632 * @param mediaRegistry The XML settings structure to load, either from VirtualBox.xml
633 * or a machine XML.
634 * @return
635 */
636HRESULT VirtualBox::initMedia(const Guid &uuidRegistry,
637 const settings::MediaRegistry mediaRegistry,
638 const Utf8Str &strMachineFolder)
639{
640 LogFlow(("VirtualBox::initMedia ENTERING, uuidRegistry=%s, strMachineFolder=%s\n",
641 uuidRegistry.toString().c_str(),
642 strMachineFolder.c_str()));
643
644 AutoWriteLock treeLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
645
646 HRESULT rc = S_OK;
647 settings::MediaList::const_iterator it;
648 for (it = mediaRegistry.llHardDisks.begin();
649 it != mediaRegistry.llHardDisks.end();
650 ++it)
651 {
652 const settings::Medium &xmlHD = *it;
653
654 ComObjPtr<Medium> pHardDisk;
655 if (SUCCEEDED(rc = pHardDisk.createObject()))
656 rc = pHardDisk->init(this,
657 NULL, // parent
658 DeviceType_HardDisk,
659 uuidRegistry,
660 xmlHD, // XML data; this recurses to processes the children
661 strMachineFolder);
662 if (FAILED(rc)) return rc;
663
664 rc = registerHardDisk(pHardDisk, NULL /* pllRegistriesThatNeedSaving */);
665 if (FAILED(rc)) return rc;
666 }
667
668 for (it = mediaRegistry.llDvdImages.begin();
669 it != mediaRegistry.llDvdImages.end();
670 ++it)
671 {
672 const settings::Medium &xmlDvd = *it;
673
674 ComObjPtr<Medium> pImage;
675 if (SUCCEEDED(pImage.createObject()))
676 rc = pImage->init(this,
677 NULL,
678 DeviceType_DVD,
679 uuidRegistry,
680 xmlDvd,
681 strMachineFolder);
682 if (FAILED(rc)) return rc;
683
684 rc = registerImage(pImage,
685 DeviceType_DVD,
686 NULL /* pllRegistriesThatNeedSaving */);
687 if (FAILED(rc)) return rc;
688 }
689
690 for (it = mediaRegistry.llFloppyImages.begin();
691 it != mediaRegistry.llFloppyImages.end();
692 ++it)
693 {
694 const settings::Medium &xmlFloppy = *it;
695
696 ComObjPtr<Medium> pImage;
697 if (SUCCEEDED(pImage.createObject()))
698 rc = pImage->init(this,
699 NULL,
700 DeviceType_Floppy,
701 uuidRegistry,
702 xmlFloppy,
703 strMachineFolder);
704 if (FAILED(rc)) return rc;
705
706 rc = registerImage(pImage,
707 DeviceType_Floppy,
708 NULL /* pllRegistriesThatNeedSaving */);
709 if (FAILED(rc)) return rc;
710 }
711
712 LogFlow(("VirtualBox::initMedia LEAVING\n"));
713
714 return S_OK;
715}
716
717void VirtualBox::uninit()
718{
719 /* Enclose the state transition Ready->InUninit->NotReady */
720 AutoUninitSpan autoUninitSpan(this);
721 if (autoUninitSpan.uninitDone())
722 return;
723
724 LogFlow(("===========================================================\n"));
725 LogFlowThisFuncEnter();
726 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
727
728 /* tell all our child objects we've been uninitialized */
729
730 LogFlowThisFunc(("Uninitializing machines (%d)...\n", m->allMachines.size()));
731 if (m->pHost)
732 {
733 /* It is necessary to hold the VirtualBox and Host locks here because
734 we may have to uninitialize SessionMachines. */
735 AutoMultiWriteLock2 multilock(this, m->pHost COMMA_LOCKVAL_SRC_POS);
736 m->allMachines.uninitAll();
737 }
738 else
739 m->allMachines.uninitAll();
740 m->allFloppyImages.uninitAll();
741 m->allDVDImages.uninitAll();
742 m->allHardDisks.uninitAll();
743 m->allDHCPServers.uninitAll();
744
745 m->mapProgressOperations.clear();
746
747 m->allGuestOSTypes.uninitAll();
748
749 /* Note that we release singleton children after we've all other children.
750 * In some cases this is important because these other children may use
751 * some resources of the singletons which would prevent them from
752 * uninitializing (as for example, mSystemProperties which owns
753 * MediumFormat objects which Medium objects refer to) */
754 if (m->pSystemProperties)
755 {
756 m->pSystemProperties->uninit();
757 unconst(m->pSystemProperties).setNull();
758 }
759
760 if (m->pHost)
761 {
762 m->pHost->uninit();
763 unconst(m->pHost).setNull();
764 }
765
766#ifdef VBOX_WITH_RESOURCE_USAGE_API
767 if (m->pPerformanceCollector)
768 {
769 m->pPerformanceCollector->uninit();
770 unconst(m->pPerformanceCollector).setNull();
771 }
772#endif /* VBOX_WITH_RESOURCE_USAGE_API */
773
774 LogFlowThisFunc(("Terminating the async event handler...\n"));
775 if (m->threadAsyncEvent != NIL_RTTHREAD)
776 {
777 /* signal to exit the event loop */
778 if (RT_SUCCESS(m->pAsyncEventQ->interruptEventQueueProcessing()))
779 {
780 /*
781 * Wait for thread termination (only after we've successfully
782 * interrupted the event queue processing!)
783 */
784 int vrc = RTThreadWait(m->threadAsyncEvent, 60000, NULL);
785 if (RT_FAILURE(vrc))
786 LogWarningFunc(("RTThreadWait(%RTthrd) -> %Rrc\n",
787 m->threadAsyncEvent, vrc));
788 }
789 else
790 {
791 AssertMsgFailed(("interruptEventQueueProcessing() failed\n"));
792 RTThreadWait(m->threadAsyncEvent, 0, NULL);
793 }
794
795 unconst(m->threadAsyncEvent) = NIL_RTTHREAD;
796 unconst(m->pAsyncEventQ) = NULL;
797 }
798
799 LogFlowThisFunc(("Releasing event source...\n"));
800 if (m->pEventSource)
801 {
802 // we don't perform uninit() as it's possible that some pending event refers to this source
803 unconst(m->pEventSource).setNull();
804 }
805
806 LogFlowThisFunc(("Terminating the client watcher...\n"));
807 if (m->threadClientWatcher != NIL_RTTHREAD)
808 {
809 /* signal the client watcher thread */
810 updateClientWatcher();
811 /* wait for the termination */
812 RTThreadWait(m->threadClientWatcher, RT_INDEFINITE_WAIT, NULL);
813 unconst(m->threadClientWatcher) = NIL_RTTHREAD;
814 }
815 m->llProcesses.clear();
816#if defined(RT_OS_WINDOWS)
817 if (m->updateReq != NULL)
818 {
819 ::CloseHandle(m->updateReq);
820 unconst(m->updateReq) = NULL;
821 }
822#elif defined(RT_OS_OS2)
823 if (m->updateReq != NIL_RTSEMEVENT)
824 {
825 RTSemEventDestroy(m->updateReq);
826 unconst(m->updateReq) = NIL_RTSEMEVENT;
827 }
828#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
829 if (m->updateReq != NIL_RTSEMEVENT)
830 {
831 RTSemEventDestroy(m->updateReq);
832 unconst(m->updateReq) = NIL_RTSEMEVENT;
833 }
834#else
835# error "Port me!"
836#endif
837
838 // clean up our instance data
839 delete m;
840
841 /* Unload hard disk plugin backends. */
842 VDShutdown();
843
844 LogFlowThisFuncLeave();
845 LogFlow(("===========================================================\n"));
846}
847
848// IVirtualBox properties
849/////////////////////////////////////////////////////////////////////////////
850
851STDMETHODIMP VirtualBox::COMGETTER(Version)(BSTR *aVersion)
852{
853 CheckComArgNotNull(aVersion);
854
855 AutoCaller autoCaller(this);
856 if (FAILED(autoCaller.rc())) return autoCaller.rc();
857
858 sVersion.cloneTo(aVersion);
859 return S_OK;
860}
861
862STDMETHODIMP VirtualBox::COMGETTER(Revision)(ULONG *aRevision)
863{
864 CheckComArgNotNull(aRevision);
865
866 AutoCaller autoCaller(this);
867 if (FAILED(autoCaller.rc())) return autoCaller.rc();
868
869 *aRevision = sRevision;
870 return S_OK;
871}
872
873STDMETHODIMP VirtualBox::COMGETTER(PackageType)(BSTR *aPackageType)
874{
875 CheckComArgNotNull(aPackageType);
876
877 AutoCaller autoCaller(this);
878 if (FAILED(autoCaller.rc())) return autoCaller.rc();
879
880 sPackageType.cloneTo(aPackageType);
881 return S_OK;
882}
883
884STDMETHODIMP VirtualBox::COMGETTER(HomeFolder)(BSTR *aHomeFolder)
885{
886 CheckComArgNotNull(aHomeFolder);
887
888 AutoCaller autoCaller(this);
889 if (FAILED(autoCaller.rc())) return autoCaller.rc();
890
891 /* mHomeDir is const and doesn't need a lock */
892 m->strHomeDir.cloneTo(aHomeFolder);
893 return S_OK;
894}
895
896STDMETHODIMP VirtualBox::COMGETTER(SettingsFilePath)(BSTR *aSettingsFilePath)
897{
898 CheckComArgNotNull(aSettingsFilePath);
899
900 AutoCaller autoCaller(this);
901 if (FAILED(autoCaller.rc())) return autoCaller.rc();
902
903 /* mCfgFile.mName is const and doesn't need a lock */
904 m->strSettingsFilePath.cloneTo(aSettingsFilePath);
905 return S_OK;
906}
907
908STDMETHODIMP VirtualBox::COMGETTER(Host)(IHost **aHost)
909{
910 CheckComArgOutSafeArrayPointerValid(aHost);
911
912 AutoCaller autoCaller(this);
913 if (FAILED(autoCaller.rc())) return autoCaller.rc();
914
915 /* mHost is const, no need to lock */
916 m->pHost.queryInterfaceTo(aHost);
917 return S_OK;
918}
919
920STDMETHODIMP
921VirtualBox::COMGETTER(SystemProperties)(ISystemProperties **aSystemProperties)
922{
923 CheckComArgOutSafeArrayPointerValid(aSystemProperties);
924
925 AutoCaller autoCaller(this);
926 if (FAILED(autoCaller.rc())) return autoCaller.rc();
927
928 /* mSystemProperties is const, no need to lock */
929 m->pSystemProperties.queryInterfaceTo(aSystemProperties);
930 return S_OK;
931}
932
933STDMETHODIMP
934VirtualBox::COMGETTER(Machines)(ComSafeArrayOut(IMachine *, aMachines))
935{
936 if (ComSafeArrayOutIsNull(aMachines))
937 return E_POINTER;
938
939 AutoCaller autoCaller(this);
940 if (FAILED(autoCaller.rc())) return autoCaller.rc();
941
942 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
943 SafeIfaceArray<IMachine> machines(m->allMachines.getList());
944 machines.detachTo(ComSafeArrayOutArg(aMachines));
945
946 return S_OK;
947}
948
949STDMETHODIMP VirtualBox::COMGETTER(HardDisks)(ComSafeArrayOut(IMedium *, aHardDisks))
950{
951 if (ComSafeArrayOutIsNull(aHardDisks))
952 return E_POINTER;
953
954 AutoCaller autoCaller(this);
955 if (FAILED(autoCaller.rc())) return autoCaller.rc();
956
957 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
958 SafeIfaceArray<IMedium> hardDisks(m->allHardDisks.getList());
959 hardDisks.detachTo(ComSafeArrayOutArg(aHardDisks));
960
961 return S_OK;
962}
963
964STDMETHODIMP VirtualBox::COMGETTER(DVDImages)(ComSafeArrayOut(IMedium *, aDVDImages))
965{
966 if (ComSafeArrayOutIsNull(aDVDImages))
967 return E_POINTER;
968
969 AutoCaller autoCaller(this);
970 if (FAILED(autoCaller.rc())) return autoCaller.rc();
971
972 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
973 SafeIfaceArray<IMedium> images(m->allDVDImages.getList());
974 images.detachTo(ComSafeArrayOutArg(aDVDImages));
975
976 return S_OK;
977}
978
979STDMETHODIMP VirtualBox::COMGETTER(FloppyImages)(ComSafeArrayOut(IMedium *, aFloppyImages))
980{
981 if (ComSafeArrayOutIsNull(aFloppyImages))
982 return E_POINTER;
983
984 AutoCaller autoCaller(this);
985 if (FAILED(autoCaller.rc())) return autoCaller.rc();
986
987 AutoReadLock al(m->allFloppyImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
988 SafeIfaceArray<IMedium> images(m->allFloppyImages.getList());
989 images.detachTo(ComSafeArrayOutArg(aFloppyImages));
990
991 return S_OK;
992}
993
994STDMETHODIMP VirtualBox::COMGETTER(ProgressOperations)(ComSafeArrayOut(IProgress *, aOperations))
995{
996 CheckComArgOutSafeArrayPointerValid(aOperations);
997
998 AutoCaller autoCaller(this);
999 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1000
1001 /* protect mProgressOperations */
1002 AutoReadLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
1003 SafeIfaceArray<IProgress> progress(m->mapProgressOperations);
1004 progress.detachTo(ComSafeArrayOutArg(aOperations));
1005
1006 return S_OK;
1007}
1008
1009STDMETHODIMP VirtualBox::COMGETTER(GuestOSTypes)(ComSafeArrayOut(IGuestOSType *, aGuestOSTypes))
1010{
1011 CheckComArgOutSafeArrayPointerValid(aGuestOSTypes);
1012
1013 AutoCaller autoCaller(this);
1014 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1015
1016 AutoReadLock al(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1017 SafeIfaceArray<IGuestOSType> ostypes(m->allGuestOSTypes.getList());
1018 ostypes.detachTo(ComSafeArrayOutArg(aGuestOSTypes));
1019
1020 return S_OK;
1021}
1022
1023STDMETHODIMP VirtualBox::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
1024{
1025#ifndef RT_OS_WINDOWS
1026 NOREF(aSharedFoldersSize);
1027#endif /* RT_OS_WINDOWS */
1028
1029 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
1030
1031 AutoCaller autoCaller(this);
1032 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1033
1034 return setError(E_NOTIMPL, "Not yet implemented");
1035}
1036
1037STDMETHODIMP
1038VirtualBox::COMGETTER(PerformanceCollector)(IPerformanceCollector **aPerformanceCollector)
1039{
1040#ifdef VBOX_WITH_RESOURCE_USAGE_API
1041 CheckComArgOutSafeArrayPointerValid(aPerformanceCollector);
1042
1043 AutoCaller autoCaller(this);
1044 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1045
1046 /* mPerformanceCollector is const, no need to lock */
1047 m->pPerformanceCollector.queryInterfaceTo(aPerformanceCollector);
1048
1049 return S_OK;
1050#else /* !VBOX_WITH_RESOURCE_USAGE_API */
1051 ReturnComNotImplemented();
1052#endif /* !VBOX_WITH_RESOURCE_USAGE_API */
1053}
1054
1055STDMETHODIMP
1056VirtualBox::COMGETTER(DHCPServers)(ComSafeArrayOut(IDHCPServer *, aDHCPServers))
1057{
1058 if (ComSafeArrayOutIsNull(aDHCPServers))
1059 return E_POINTER;
1060
1061 AutoCaller autoCaller(this);
1062 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1063
1064 AutoReadLock al(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1065 SafeIfaceArray<IDHCPServer> svrs(m->allDHCPServers.getList());
1066 svrs.detachTo(ComSafeArrayOutArg(aDHCPServers));
1067
1068 return S_OK;
1069}
1070
1071STDMETHODIMP
1072VirtualBox::COMGETTER(EventSource)(IEventSource ** aEventSource)
1073{
1074 CheckComArgOutPointerValid(aEventSource);
1075
1076 AutoCaller autoCaller(this);
1077 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1078
1079 /* event source is const, no need to lock */
1080 m->pEventSource.queryInterfaceTo(aEventSource);
1081
1082 return S_OK;
1083}
1084
1085STDMETHODIMP
1086VirtualBox::COMGETTER(ExtensionPackManager)(IExtPackManager **aExtPackManager)
1087{
1088 CheckComArgOutPointerValid(aExtPackManager);
1089
1090 AutoCaller autoCaller(this);
1091 HRESULT hrc = autoCaller.rc();
1092 if (SUCCEEDED(hrc))
1093 {
1094#ifdef VBOX_WITH_EXTPACK
1095 /* The extension pack manager is const, no need to lock. */
1096 hrc = m->ptrExtPackManager.queryInterfaceTo(aExtPackManager);
1097#else
1098 hrc = E_NOTIMPL;
1099#endif
1100 }
1101
1102 return hrc;
1103}
1104
1105STDMETHODIMP
1106VirtualBox::CheckFirmwarePresent(FirmwareType_T aFirmwareType,
1107 IN_BSTR aVersion,
1108 BSTR *aUrl,
1109 BSTR *aFile,
1110 BOOL *aResult)
1111{
1112 CheckComArgNotNull(aResult);
1113
1114 AutoCaller autoCaller(this);
1115 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1116
1117 const char *url;
1118
1119 NOREF(aVersion);
1120
1121 static const struct {
1122 FirmwareType_T type;
1123 const char* fileName;
1124 const char* url;
1125 }
1126 firmwareDesc[] =
1127 {
1128 {
1129 /* compiled-in firmware */
1130 FirmwareType_BIOS, NULL, NULL
1131 },
1132 {
1133 FirmwareType_EFI32, "VBoxEFI32.fd", "http://virtualbox.org/firmware/VBoxEFI32.fd"
1134 },
1135 {
1136 FirmwareType_EFI64, "VBoxEFI64.fd", "http://virtualbox.org/firmware/VBoxEFI64.fd"
1137 },
1138 {
1139 FirmwareType_EFIDUAL, "VBoxEFIDual.fd", "http://virtualbox.org/firmware/VBoxEFIDual.fd"
1140 }
1141 };
1142
1143 for (size_t i = 0; i < sizeof(firmwareDesc) / sizeof(firmwareDesc[0]); i++)
1144 {
1145 if (aFirmwareType != firmwareDesc[i].type)
1146 continue;
1147
1148 /* compiled-in firmware */
1149 if (firmwareDesc[i].fileName == NULL)
1150 {
1151 *aResult = TRUE;
1152 break;
1153 }
1154
1155 Utf8Str shortName, fullName;
1156 int rc;
1157
1158 shortName = Utf8StrFmt("Firmware%c%s",
1159 RTPATH_DELIMITER,
1160 firmwareDesc[i].fileName);
1161 rc = calculateFullPath(shortName, fullName); AssertRCReturn(rc, rc);
1162 if (RTFileExists(fullName.c_str()))
1163 {
1164 *aResult = TRUE;
1165 if (aFile)
1166 Utf8Str(fullName).cloneTo(aFile);
1167 break;
1168 }
1169
1170 char pszVBoxPath[RTPATH_MAX];
1171 rc = RTPathExecDir(pszVBoxPath, RTPATH_MAX); AssertRCReturn(rc, rc);
1172 fullName = Utf8StrFmt("%s%c%s",
1173 pszVBoxPath,
1174 RTPATH_DELIMITER,
1175 firmwareDesc[i].fileName);
1176 if (RTFileExists(fullName.c_str()))
1177 {
1178 *aResult = TRUE;
1179 if (aFile)
1180 Utf8Str(fullName).cloneTo(aFile);
1181 break;
1182 }
1183
1184
1185 url = firmwareDesc[i].url;
1186 /** @todo: account for version in the URL */
1187 if (aUrl != NULL)
1188 {
1189 Utf8Str strUrl(firmwareDesc[i].url);
1190 strUrl.cloneTo(aUrl);
1191 }
1192 *aResult = FALSE;
1193
1194 /* Assume single record per firmware type */
1195 break;
1196 }
1197
1198 return S_OK;
1199}
1200// IVirtualBox methods
1201/////////////////////////////////////////////////////////////////////////////
1202
1203STDMETHODIMP VirtualBox::ComposeMachineFilename(IN_BSTR aName,
1204 IN_BSTR aBaseFolder,
1205 BSTR *aFilename)
1206{
1207 LogFlowThisFuncEnter();
1208 LogFlowThisFunc(("aName=\"%ls\",aBaseFolder=\"%ls\"\n", aName, aBaseFolder));
1209
1210 CheckComArgStrNotEmptyOrNull(aName);
1211 CheckComArgOutPointerValid(aFilename);
1212
1213 AutoCaller autoCaller(this);
1214 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1215
1216 /* Compose the settings file name using the following scheme:
1217 *
1218 * <base_folder>/<machine_name>/<machine_name>.xml
1219 *
1220 * If a non-null and non-empty base folder is specified, the default
1221 * machine folder will be used as a base folder.
1222 */
1223 Utf8Str strBase = aBaseFolder;
1224 if (strBase.isEmpty())
1225 /* we use the non-full folder value below to keep the path relative */
1226 getDefaultMachineFolder(strBase);
1227
1228 calculateFullPath(strBase, strBase);
1229
1230 Bstr bstrSettingsFile = BstrFmt("%s%c%ls%c%ls.vbox",
1231 strBase.c_str(),
1232 RTPATH_DELIMITER,
1233 aName,
1234 RTPATH_DELIMITER,
1235 aName);
1236
1237 bstrSettingsFile.detachTo(aFilename);
1238
1239 return S_OK;
1240}
1241
1242/** @note Locks mSystemProperties object for reading. */
1243STDMETHODIMP VirtualBox::CreateMachine(IN_BSTR aSettingsFile,
1244 IN_BSTR aName,
1245 IN_BSTR aOsTypeId,
1246 IN_BSTR aId,
1247 BOOL forceOverwrite,
1248 IMachine **aMachine)
1249{
1250 LogFlowThisFuncEnter();
1251 LogFlowThisFunc(("aSettingsFile=\"%ls\", aName=\"%ls\", aOsTypeId =\"%ls\"\n", aSettingsFile, aName, aOsTypeId));
1252
1253 CheckComArgStrNotEmptyOrNull(aName);
1254 /** @todo tighten checks on aId? */
1255 CheckComArgOutPointerValid(aMachine);
1256
1257 AutoCaller autoCaller(this);
1258 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1259
1260 /* NULL settings file means compose automatically */
1261 HRESULT rc;
1262 Bstr bstrSettingsFile(aSettingsFile);
1263 if (bstrSettingsFile.isEmpty())
1264 {
1265 rc = ComposeMachineFilename(aName,
1266 NULL,
1267 bstrSettingsFile.asOutParam());
1268 if (FAILED(rc)) return rc;
1269 }
1270
1271 /* create a new object */
1272 ComObjPtr<Machine> machine;
1273 rc = machine.createObject();
1274 if (FAILED(rc)) return rc;
1275
1276 /* Create UUID if an empty one was specified. */
1277 Guid id(aId);
1278 if (id.isEmpty())
1279 id.create();
1280
1281 GuestOSType *osType = NULL;
1282 rc = findGuestOSType(Bstr(aOsTypeId), osType);
1283 if (FAILED(rc)) return rc;
1284
1285 /* initialize the machine object */
1286 rc = machine->init(this,
1287 Utf8Str(bstrSettingsFile),
1288 Utf8Str(aName),
1289 osType,
1290 id,
1291 !!forceOverwrite);
1292 if (SUCCEEDED(rc))
1293 {
1294 /* set the return value */
1295 rc = machine.queryInterfaceTo(aMachine);
1296 AssertComRC(rc);
1297
1298#ifdef VBOX_WITH_EXTPACK
1299 /* call the extension pack hooks */
1300 m->ptrExtPackManager->callAllVmCreatedHooks(machine);
1301#endif
1302 }
1303
1304 LogFlowThisFuncLeave();
1305
1306 return rc;
1307}
1308
1309STDMETHODIMP VirtualBox::OpenMachine(IN_BSTR aSettingsFile,
1310 IMachine **aMachine)
1311{
1312 CheckComArgStrNotEmptyOrNull(aSettingsFile);
1313 CheckComArgOutSafeArrayPointerValid(aMachine);
1314
1315 AutoCaller autoCaller(this);
1316 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1317
1318 HRESULT rc = E_FAIL;
1319
1320 /* create a new object */
1321 ComObjPtr<Machine> machine;
1322 rc = machine.createObject();
1323 if (SUCCEEDED(rc))
1324 {
1325 /* initialize the machine object */
1326 rc = machine->init(this,
1327 aSettingsFile,
1328 NULL); /* const Guid *aId */
1329 if (SUCCEEDED(rc))
1330 {
1331 /* set the return value */
1332 rc = machine.queryInterfaceTo(aMachine);
1333 ComAssertComRC(rc);
1334 }
1335 }
1336
1337 return rc;
1338}
1339
1340/** @note Locks objects! */
1341STDMETHODIMP VirtualBox::RegisterMachine(IMachine *aMachine)
1342{
1343 CheckComArgNotNull(aMachine);
1344
1345 AutoCaller autoCaller(this);
1346 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1347
1348 HRESULT rc;
1349
1350 Bstr name;
1351 rc = aMachine->COMGETTER(Name)(name.asOutParam());
1352 if (FAILED(rc)) return rc;
1353
1354 /* We can safely cast child to Machine * here because only Machine
1355 * implementations of IMachine can be among our children. */
1356 Machine *pMachine = static_cast<Machine*>(aMachine);
1357
1358 AutoCaller machCaller(pMachine);
1359 ComAssertComRCRetRC(machCaller.rc());
1360
1361 rc = registerMachine(pMachine);
1362 /* fire an event */
1363 if (SUCCEEDED(rc))
1364 onMachineRegistered(pMachine->getId(), TRUE);
1365
1366 return rc;
1367}
1368
1369/** @note Locks this object for reading, then some machine objects for reading. */
1370STDMETHODIMP VirtualBox::FindMachine(IN_BSTR aNameOrId, IMachine **aMachine)
1371{
1372 LogFlowThisFuncEnter();
1373 LogFlowThisFunc(("aName=\"%ls\", aMachine={%p}\n", aNameOrId, aMachine));
1374
1375 CheckComArgStrNotEmptyOrNull(aNameOrId);
1376 CheckComArgOutSafeArrayPointerValid(aMachine);
1377
1378 AutoCaller autoCaller(this);
1379 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1380
1381 /* start with not found */
1382 HRESULT rc = S_OK;
1383 ComObjPtr<Machine> pMachineFound;
1384
1385 Guid id(aNameOrId);
1386 if (!id.isEmpty())
1387 rc = findMachine(id,
1388 true /* fPermitInaccessible */,
1389 true /* setError */,
1390 &pMachineFound);
1391 // returns VBOX_E_OBJECT_NOT_FOUND if not found and sets error
1392 else
1393 {
1394 Utf8Str strName(aNameOrId);
1395 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1396 for (MachinesOList::iterator it = m->allMachines.begin();
1397 it != m->allMachines.end();
1398 ++it)
1399 {
1400 ComObjPtr<Machine> &pMachine2 = *it;
1401 AutoCaller machCaller(pMachine2);
1402 if (machCaller.rc())
1403 continue; // we can't ask inaccessible machines for their names
1404
1405 AutoReadLock machLock(pMachine2 COMMA_LOCKVAL_SRC_POS);
1406 if (pMachine2->getName() == strName)
1407 {
1408 pMachineFound = pMachine2;
1409 break;
1410 }
1411 if (!RTPathCompare(pMachine2->getSettingsFileFull().c_str(), strName.c_str()))
1412 {
1413 pMachineFound = pMachine2;
1414 break;
1415 }
1416 }
1417
1418 if (!pMachineFound)
1419 rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1420 tr("Could not find a registered machine named '%ls'"), aNameOrId);
1421 }
1422
1423 /* this will set (*machine) to NULL if machineObj is null */
1424 pMachineFound.queryInterfaceTo(aMachine);
1425
1426 LogFlowThisFunc(("aName=\"%ls\", aMachine=%p, rc=%08X\n", aNameOrId, *aMachine, rc));
1427 LogFlowThisFuncLeave();
1428
1429 return rc;
1430}
1431
1432STDMETHODIMP VirtualBox::CreateHardDisk(IN_BSTR aFormat,
1433 IN_BSTR aLocation,
1434 IMedium **aHardDisk)
1435{
1436 CheckComArgOutPointerValid(aHardDisk);
1437
1438 AutoCaller autoCaller(this);
1439 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1440
1441 /* we don't access non-const data members so no need to lock */
1442
1443 Utf8Str format(aFormat);
1444 if (format.isEmpty())
1445 getDefaultHardDiskFormat(format);
1446
1447 ComObjPtr<Medium> hardDisk;
1448 hardDisk.createObject();
1449 HRESULT rc = hardDisk->init(this,
1450 format,
1451 aLocation,
1452 Guid::Empty, // media registry: none yet
1453 NULL /* pllRegistriesThatNeedSaving */);
1454
1455 if (SUCCEEDED(rc))
1456 hardDisk.queryInterfaceTo(aHardDisk);
1457
1458 return rc;
1459}
1460
1461STDMETHODIMP VirtualBox::OpenMedium(IN_BSTR aLocation,
1462 DeviceType_T deviceType,
1463 AccessMode_T accessMode,
1464 IMedium **aMedium)
1465{
1466 CheckComArgStrNotEmptyOrNull(aLocation);
1467 CheckComArgOutSafeArrayPointerValid(aMedium);
1468
1469 AutoCaller autoCaller(this);
1470 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1471
1472 ComObjPtr<Medium> pMedium;
1473
1474 /* we don't access non-const data members so no need to lock */
1475
1476 // check if the device type is correct, and see if a medium for the
1477 // given path has already initialized; if so, return that
1478 switch (deviceType)
1479 {
1480 case DeviceType_HardDisk:
1481 findHardDiskByLocation(aLocation,
1482 false, /* aSetError */
1483 &pMedium);
1484 break;
1485
1486 case DeviceType_Floppy:
1487 case DeviceType_DVD:
1488 findDVDOrFloppyImage(deviceType,
1489 NULL, /* guid */
1490 aLocation,
1491 false, /* aSetError */
1492 &pMedium);
1493
1494 // enforce read-only for DVDs even if caller specified ReadWrite
1495 if (deviceType == DeviceType_DVD)
1496 accessMode = AccessMode_ReadOnly;
1497 break;
1498
1499 default:
1500 return setError(E_INVALIDARG, "Device type must be HardDisk, DVD or Floppy");
1501 }
1502
1503 HRESULT rc = S_OK;
1504
1505 if (pMedium.isNull())
1506 {
1507 pMedium.createObject();
1508 rc = pMedium->init(this,
1509 aLocation,
1510 (accessMode == AccessMode_ReadWrite) ? Medium::OpenReadWrite : Medium::OpenReadOnly,
1511 deviceType);
1512
1513 if (SUCCEEDED(rc))
1514 {
1515 AutoWriteLock treeLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1516
1517 switch (deviceType)
1518 {
1519 case DeviceType_HardDisk:
1520 rc = registerHardDisk(pMedium, NULL /* pllRegistriesThatNeedSaving */);
1521 break;
1522
1523 case DeviceType_DVD:
1524 case DeviceType_Floppy:
1525 rc = registerImage(pMedium,
1526 deviceType,
1527 NULL /* pllRegistriesThatNeedSaving */);
1528 break;
1529 }
1530
1531 treeLock.release();
1532
1533 /* Note that it's important to call uninit() on failure to register
1534 * because the differencing hard disk would have been already associated
1535 * with the parent and this association needs to be broken. */
1536
1537 if (FAILED(rc))
1538 pMedium->uninit();
1539 }
1540 }
1541
1542 if (SUCCEEDED(rc))
1543 pMedium.queryInterfaceTo(aMedium);
1544
1545 return rc;
1546}
1547
1548STDMETHODIMP VirtualBox::FindMedium(IN_BSTR aLocation,
1549 DeviceType_T aDeviceType,
1550 IMedium **aMedium)
1551{
1552 CheckComArgStrNotEmptyOrNull(aLocation);
1553 CheckComArgOutSafeArrayPointerValid(aMedium);
1554
1555 AutoCaller autoCaller(this);
1556 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1557
1558 Guid id(aLocation);
1559 Utf8Str strLocation(aLocation);
1560
1561 HRESULT rc;
1562 ComObjPtr<Medium> pMedium;
1563
1564 switch (aDeviceType)
1565 {
1566 case DeviceType_HardDisk:
1567 if (!id.isEmpty())
1568 rc = findHardDiskById(id, true /* setError */, &pMedium);
1569 else
1570 rc = findHardDiskByLocation(strLocation, true /* setError */, &pMedium);
1571 break;
1572
1573 case DeviceType_Floppy:
1574 case DeviceType_DVD:
1575 if (!id.isEmpty())
1576 rc = findDVDOrFloppyImage(aDeviceType, &id, Utf8Str::Empty, true /* setError */, &pMedium);
1577 else
1578 rc = findDVDOrFloppyImage(aDeviceType, NULL, strLocation, true /* setError */, &pMedium);
1579 break;
1580
1581 default:
1582 return setError(E_INVALIDARG,
1583 tr("Invalid device type %d"), aDeviceType);
1584 }
1585
1586 /* the below will set *aHardDisk to NULL if hardDisk is null */
1587 pMedium.queryInterfaceTo(aMedium);
1588
1589 return rc;
1590}
1591
1592/** @note Locks this object for reading. */
1593STDMETHODIMP VirtualBox::GetGuestOSType(IN_BSTR aId, IGuestOSType **aType)
1594{
1595 /* Old ID to new ID conversion table. See r39691 for a source */
1596 static const wchar_t *kOldNewIDs[] =
1597 {
1598 L"unknown", L"Other",
1599 L"win31", L"Windows31",
1600 L"win95", L"Windows95",
1601 L"win98", L"Windows98",
1602 L"winme", L"WindowsMe",
1603 L"winnt4", L"WindowsNT4",
1604 L"win2k", L"Windows2000",
1605 L"winxp", L"WindowsXP",
1606 L"win2k3", L"Windows2003",
1607 L"winvista", L"WindowsVista",
1608 L"win2k8", L"Windows2008",
1609 L"ecs", L"OS2eCS",
1610 L"fedoracore", L"Fedora",
1611 /* the rest is covered by the case-insensitive comparison */
1612 };
1613
1614 CheckComArgNotNull(aType);
1615
1616 AutoCaller autoCaller(this);
1617 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1618
1619 /* first, look for a substitution */
1620 Bstr id = aId;
1621 for (size_t i = 0; i < RT_ELEMENTS(kOldNewIDs) / 2; i += 2)
1622 {
1623 if (id == kOldNewIDs[i])
1624 {
1625 id = kOldNewIDs[i + 1];
1626 break;
1627 }
1628 }
1629
1630 *aType = NULL;
1631
1632 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1633 for (GuestOSTypesOList::iterator it = m->allGuestOSTypes.begin();
1634 it != m->allGuestOSTypes.end();
1635 ++it)
1636 {
1637 const Bstr &typeId = (*it)->id();
1638 AssertMsg(!typeId.isEmpty(), ("ID must not be NULL"));
1639 if (typeId.compare(id, Bstr::CaseInsensitive) == 0)
1640 {
1641 (*it).queryInterfaceTo(aType);
1642 break;
1643 }
1644 }
1645
1646 return (*aType) ? S_OK :
1647 setError(E_INVALIDARG,
1648 tr("'%ls' is not a valid Guest OS type"),
1649 aId);
1650}
1651
1652STDMETHODIMP VirtualBox::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath,
1653 BOOL /* aWritable */, BOOL /* aAutoMount */)
1654{
1655 CheckComArgStrNotEmptyOrNull(aName);
1656 CheckComArgStrNotEmptyOrNull(aHostPath);
1657
1658 AutoCaller autoCaller(this);
1659 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1660
1661 return setError(E_NOTIMPL, "Not yet implemented");
1662}
1663
1664STDMETHODIMP VirtualBox::RemoveSharedFolder(IN_BSTR aName)
1665{
1666 CheckComArgStrNotEmptyOrNull(aName);
1667
1668 AutoCaller autoCaller(this);
1669 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1670
1671 return setError(E_NOTIMPL, "Not yet implemented");
1672}
1673
1674/**
1675 * @note Locks this object for reading.
1676 */
1677STDMETHODIMP VirtualBox::GetExtraDataKeys(ComSafeArrayOut(BSTR, aKeys))
1678{
1679 using namespace settings;
1680
1681 if (ComSafeArrayOutIsNull(aKeys))
1682 return E_POINTER;
1683
1684 AutoCaller autoCaller(this);
1685 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1686
1687 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1688
1689 com::SafeArray<BSTR> saKeys(m->pMainConfigFile->mapExtraDataItems.size());
1690 int i = 0;
1691 for (StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.begin();
1692 it != m->pMainConfigFile->mapExtraDataItems.end();
1693 ++it, ++i)
1694 {
1695 const Utf8Str &strName = it->first; // the key
1696 strName.cloneTo(&saKeys[i]);
1697 }
1698 saKeys.detachTo(ComSafeArrayOutArg(aKeys));
1699
1700 return S_OK;
1701}
1702
1703/**
1704 * @note Locks this object for reading.
1705 */
1706STDMETHODIMP VirtualBox::GetExtraData(IN_BSTR aKey,
1707 BSTR *aValue)
1708{
1709 CheckComArgStrNotEmptyOrNull(aKey);
1710 CheckComArgNotNull(aValue);
1711
1712 AutoCaller autoCaller(this);
1713 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1714
1715 /* start with nothing found */
1716 Utf8Str strKey(aKey);
1717 Bstr bstrResult;
1718
1719 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1720 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1721 // found:
1722 bstrResult = it->second; // source is a Utf8Str
1723
1724 /* return the result to caller (may be empty) */
1725 bstrResult.cloneTo(aValue);
1726
1727 return S_OK;
1728}
1729
1730/**
1731 * @note Locks this object for writing.
1732 */
1733STDMETHODIMP VirtualBox::SetExtraData(IN_BSTR aKey,
1734 IN_BSTR aValue)
1735{
1736 CheckComArgStrNotEmptyOrNull(aKey);
1737
1738 AutoCaller autoCaller(this);
1739 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1740
1741 Utf8Str strKey(aKey);
1742 Utf8Str strValue(aValue);
1743 Utf8Str strOldValue; // empty
1744
1745 // locking note: we only hold the read lock briefly to look up the old value,
1746 // then release it and call the onExtraCanChange callbacks. There is a small
1747 // chance of a race insofar as the callback might be called twice if two callers
1748 // change the same key at the same time, but that's a much better solution
1749 // than the deadlock we had here before. The actual changing of the extradata
1750 // is then performed under the write lock and race-free.
1751
1752 // look up the old value first; if nothing has changed then we need not do anything
1753 {
1754 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS); // hold read lock only while looking up
1755 settings::StringsMap::const_iterator it = m->pMainConfigFile->mapExtraDataItems.find(strKey);
1756 if (it != m->pMainConfigFile->mapExtraDataItems.end())
1757 strOldValue = it->second;
1758 }
1759
1760 bool fChanged;
1761 if ((fChanged = (strOldValue != strValue)))
1762 {
1763 // ask for permission from all listeners outside the locks;
1764 // onExtraDataCanChange() only briefly requests the VirtualBox
1765 // lock to copy the list of callbacks to invoke
1766 Bstr error;
1767 Bstr bstrValue(aValue);
1768
1769 if (!onExtraDataCanChange(Guid::Empty, aKey, bstrValue.raw(), error))
1770 {
1771 const char *sep = error.isEmpty() ? "" : ": ";
1772 CBSTR err = error.raw();
1773 LogWarningFunc(("Someone vetoed! Change refused%s%ls\n",
1774 sep, err));
1775 return setError(E_ACCESSDENIED,
1776 tr("Could not set extra data because someone refused the requested change of '%ls' to '%ls'%s%ls"),
1777 aKey,
1778 bstrValue.raw(),
1779 sep,
1780 err);
1781 }
1782
1783 // data is changing and change not vetoed: then write it out under the lock
1784
1785 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1786
1787 if (strValue.isEmpty())
1788 m->pMainConfigFile->mapExtraDataItems.erase(strKey);
1789 else
1790 m->pMainConfigFile->mapExtraDataItems[strKey] = strValue;
1791 // creates a new key if needed
1792
1793 /* save settings on success */
1794 HRESULT rc = saveSettings();
1795 if (FAILED(rc)) return rc;
1796 }
1797
1798 // fire notification outside the lock
1799 if (fChanged)
1800 onExtraDataChange(Guid::Empty, aKey, aValue);
1801
1802 return S_OK;
1803}
1804
1805// public methods only for internal purposes
1806/////////////////////////////////////////////////////////////////////////////
1807
1808#ifdef DEBUG
1809void VirtualBox::dumpAllBackRefs()
1810{
1811 {
1812 AutoReadLock al(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1813 for (MediaList::const_iterator mt = m->allHardDisks.begin();
1814 mt != m->allHardDisks.end();
1815 ++mt)
1816 {
1817 ComObjPtr<Medium> pMedium = *mt;
1818 pMedium->dumpBackRefs();
1819 }
1820 }
1821 {
1822 AutoReadLock al(m->allDVDImages.getLockHandle() COMMA_LOCKVAL_SRC_POS);
1823 for (MediaList::const_iterator mt = m->allDVDImages.begin();
1824 mt != m->allDVDImages.end();
1825 ++mt)
1826 {
1827 ComObjPtr<Medium> pMedium = *mt;
1828 pMedium->dumpBackRefs();
1829 }
1830 }
1831}
1832#endif
1833
1834/**
1835 * Posts an event to the event queue that is processed asynchronously
1836 * on a dedicated thread.
1837 *
1838 * Posting events to the dedicated event queue is useful to perform secondary
1839 * actions outside any object locks -- for example, to iterate over a list
1840 * of callbacks and inform them about some change caused by some object's
1841 * method call.
1842 *
1843 * @param event event to post; must have been allocated using |new|, will
1844 * be deleted automatically by the event thread after processing
1845 *
1846 * @note Doesn't lock any object.
1847 */
1848HRESULT VirtualBox::postEvent(Event *event)
1849{
1850 AssertReturn(event, E_FAIL);
1851
1852 HRESULT rc;
1853 AutoCaller autoCaller(this);
1854 if (SUCCEEDED((rc = autoCaller.rc())))
1855 {
1856 if (autoCaller.state() != Ready)
1857 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the event is discarded!\n",
1858 autoCaller.state()));
1859 // return S_OK
1860 else if ( (m->pAsyncEventQ)
1861 && (m->pAsyncEventQ->postEvent(event))
1862 )
1863 return S_OK;
1864 else
1865 rc = E_FAIL;
1866 }
1867
1868 // in any event of failure, we must clean up here, or we'll leak;
1869 // the caller has allocated the object using new()
1870 delete event;
1871 return rc;
1872}
1873
1874/**
1875 * Adds a progress to the global collection of pending operations.
1876 * Usually gets called upon progress object initialization.
1877 *
1878 * @param aProgress Operation to add to the collection.
1879 *
1880 * @note Doesn't lock objects.
1881 */
1882HRESULT VirtualBox::addProgress(IProgress *aProgress)
1883{
1884 CheckComArgNotNull(aProgress);
1885
1886 AutoCaller autoCaller(this);
1887 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1888
1889 Bstr id;
1890 HRESULT rc = aProgress->COMGETTER(Id)(id.asOutParam());
1891 AssertComRCReturnRC(rc);
1892
1893 /* protect mProgressOperations */
1894 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
1895
1896 m->mapProgressOperations.insert(ProgressMap::value_type(Guid(id), aProgress));
1897 return S_OK;
1898}
1899
1900/**
1901 * Removes the progress from the global collection of pending operations.
1902 * Usually gets called upon progress completion.
1903 *
1904 * @param aId UUID of the progress operation to remove
1905 *
1906 * @note Doesn't lock objects.
1907 */
1908HRESULT VirtualBox::removeProgress(IN_GUID aId)
1909{
1910 AutoCaller autoCaller(this);
1911 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1912
1913 ComPtr<IProgress> progress;
1914
1915 /* protect mProgressOperations */
1916 AutoWriteLock safeLock(m->mtxProgressOperations COMMA_LOCKVAL_SRC_POS);
1917
1918 size_t cnt = m->mapProgressOperations.erase(aId);
1919 Assert(cnt == 1);
1920 NOREF(cnt);
1921
1922 return S_OK;
1923}
1924
1925#ifdef RT_OS_WINDOWS
1926
1927struct StartSVCHelperClientData
1928{
1929 ComObjPtr<VirtualBox> that;
1930 ComObjPtr<Progress> progress;
1931 bool privileged;
1932 VirtualBox::SVCHelperClientFunc func;
1933 void *user;
1934};
1935
1936/**
1937 * Helper method that starts a worker thread that:
1938 * - creates a pipe communication channel using SVCHlpClient;
1939 * - starts an SVC Helper process that will inherit this channel;
1940 * - executes the supplied function by passing it the created SVCHlpClient
1941 * and opened instance to communicate to the Helper process and the given
1942 * Progress object.
1943 *
1944 * The user function is supposed to communicate to the helper process
1945 * using the \a aClient argument to do the requested job and optionally expose
1946 * the progress through the \a aProgress object. The user function should never
1947 * call notifyComplete() on it: this will be done automatically using the
1948 * result code returned by the function.
1949 *
1950 * Before the user function is started, the communication channel passed to
1951 * the \a aClient argument is fully set up, the function should start using
1952 * its write() and read() methods directly.
1953 *
1954 * The \a aVrc parameter of the user function may be used to return an error
1955 * code if it is related to communication errors (for example, returned by
1956 * the SVCHlpClient members when they fail). In this case, the correct error
1957 * message using this value will be reported to the caller. Note that the
1958 * value of \a aVrc is inspected only if the user function itself returns
1959 * success.
1960 *
1961 * If a failure happens anywhere before the user function would be normally
1962 * called, it will be called anyway in special "cleanup only" mode indicated
1963 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
1964 * all the function is supposed to do is to cleanup its aUser argument if
1965 * necessary (it's assumed that the ownership of this argument is passed to
1966 * the user function once #startSVCHelperClient() returns a success, thus
1967 * making it responsible for the cleanup).
1968 *
1969 * After the user function returns, the thread will send the SVCHlpMsg::Null
1970 * message to indicate a process termination.
1971 *
1972 * @param aPrivileged |true| to start the SVC Helper process as a privileged
1973 * user that can perform administrative tasks
1974 * @param aFunc user function to run
1975 * @param aUser argument to the user function
1976 * @param aProgress progress object that will track operation completion
1977 *
1978 * @note aPrivileged is currently ignored (due to some unsolved problems in
1979 * Vista) and the process will be started as a normal (unprivileged)
1980 * process.
1981 *
1982 * @note Doesn't lock anything.
1983 */
1984HRESULT VirtualBox::startSVCHelperClient(bool aPrivileged,
1985 SVCHelperClientFunc aFunc,
1986 void *aUser, Progress *aProgress)
1987{
1988 AssertReturn(aFunc, E_POINTER);
1989 AssertReturn(aProgress, E_POINTER);
1990
1991 AutoCaller autoCaller(this);
1992 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1993
1994 /* create the SVCHelperClientThread() argument */
1995 std::auto_ptr <StartSVCHelperClientData>
1996 d(new StartSVCHelperClientData());
1997 AssertReturn(d.get(), E_OUTOFMEMORY);
1998
1999 d->that = this;
2000 d->progress = aProgress;
2001 d->privileged = aPrivileged;
2002 d->func = aFunc;
2003 d->user = aUser;
2004
2005 RTTHREAD tid = NIL_RTTHREAD;
2006 int vrc = RTThreadCreate(&tid, SVCHelperClientThread,
2007 static_cast <void *>(d.get()),
2008 0, RTTHREADTYPE_MAIN_WORKER,
2009 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2010 if (RT_FAILURE(vrc))
2011 return setError(E_FAIL, "Could not create SVCHelper thread (%Rrc)", vrc);
2012
2013 /* d is now owned by SVCHelperClientThread(), so release it */
2014 d.release();
2015
2016 return S_OK;
2017}
2018
2019/**
2020 * Worker thread for startSVCHelperClient().
2021 */
2022/* static */
2023DECLCALLBACK(int)
2024VirtualBox::SVCHelperClientThread(RTTHREAD aThread, void *aUser)
2025{
2026 LogFlowFuncEnter();
2027
2028 std::auto_ptr<StartSVCHelperClientData>
2029 d(static_cast<StartSVCHelperClientData*>(aUser));
2030
2031 HRESULT rc = S_OK;
2032 bool userFuncCalled = false;
2033
2034 do
2035 {
2036 AssertBreakStmt(d.get(), rc = E_POINTER);
2037 AssertReturn(!d->progress.isNull(), E_POINTER);
2038
2039 /* protect VirtualBox from uninitialization */
2040 AutoCaller autoCaller(d->that);
2041 if (!autoCaller.isOk())
2042 {
2043 /* it's too late */
2044 rc = autoCaller.rc();
2045 break;
2046 }
2047
2048 int vrc = VINF_SUCCESS;
2049
2050 Guid id;
2051 id.create();
2052 SVCHlpClient client;
2053 vrc = client.create(Utf8StrFmt("VirtualBox\\SVCHelper\\{%RTuuid}",
2054 id.raw()).c_str());
2055 if (RT_FAILURE(vrc))
2056 {
2057 rc = d->that->setError(E_FAIL,
2058 tr("Could not create the communication channel (%Rrc)"), vrc);
2059 break;
2060 }
2061
2062 /* get the path to the executable */
2063 char exePathBuf[RTPATH_MAX];
2064 char *exePath = RTProcGetExecutablePath(exePathBuf, RTPATH_MAX);
2065 if (!exePath)
2066 {
2067 rc = d->that->setError(E_FAIL, tr("Cannot get executable name"));
2068 break;
2069 }
2070
2071 Utf8Str argsStr = Utf8StrFmt("/Helper %s", client.name().c_str());
2072
2073 LogFlowFunc(("Starting '\"%s\" %s'...\n", exePath, argsStr.c_str()));
2074
2075 RTPROCESS pid = NIL_RTPROCESS;
2076
2077 if (d->privileged)
2078 {
2079 /* Attempt to start a privileged process using the Run As dialog */
2080
2081 Bstr file = exePath;
2082 Bstr parameters = argsStr;
2083
2084 SHELLEXECUTEINFO shExecInfo;
2085
2086 shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
2087
2088 shExecInfo.fMask = NULL;
2089 shExecInfo.hwnd = NULL;
2090 shExecInfo.lpVerb = L"runas";
2091 shExecInfo.lpFile = file.raw();
2092 shExecInfo.lpParameters = parameters.raw();
2093 shExecInfo.lpDirectory = NULL;
2094 shExecInfo.nShow = SW_NORMAL;
2095 shExecInfo.hInstApp = NULL;
2096
2097 if (!ShellExecuteEx(&shExecInfo))
2098 {
2099 int vrc2 = RTErrConvertFromWin32(GetLastError());
2100 /* hide excessive details in case of a frequent error
2101 * (pressing the Cancel button to close the Run As dialog) */
2102 if (vrc2 == VERR_CANCELLED)
2103 rc = d->that->setError(E_FAIL,
2104 tr("Operation canceled by the user"));
2105 else
2106 rc = d->that->setError(E_FAIL,
2107 tr("Could not launch a privileged process '%s' (%Rrc)"),
2108 exePath, vrc2);
2109 break;
2110 }
2111 }
2112 else
2113 {
2114 const char *args[] = { exePath, "/Helper", client.name().c_str(), 0 };
2115 vrc = RTProcCreate(exePath, args, RTENV_DEFAULT, 0, &pid);
2116 if (RT_FAILURE(vrc))
2117 {
2118 rc = d->that->setError(E_FAIL,
2119 tr("Could not launch a process '%s' (%Rrc)"), exePath, vrc);
2120 break;
2121 }
2122 }
2123
2124 /* wait for the client to connect */
2125 vrc = client.connect();
2126 if (RT_SUCCESS(vrc))
2127 {
2128 /* start the user supplied function */
2129 rc = d->func(&client, d->progress, d->user, &vrc);
2130 userFuncCalled = true;
2131 }
2132
2133 /* send the termination signal to the process anyway */
2134 {
2135 int vrc2 = client.write(SVCHlpMsg::Null);
2136 if (RT_SUCCESS(vrc))
2137 vrc = vrc2;
2138 }
2139
2140 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
2141 {
2142 rc = d->that->setError(E_FAIL,
2143 tr("Could not operate the communication channel (%Rrc)"), vrc);
2144 break;
2145 }
2146 }
2147 while (0);
2148
2149 if (FAILED(rc) && !userFuncCalled)
2150 {
2151 /* call the user function in the "cleanup only" mode
2152 * to let it free resources passed to in aUser */
2153 d->func(NULL, NULL, d->user, NULL);
2154 }
2155
2156 d->progress->notifyComplete(rc);
2157
2158 LogFlowFuncLeave();
2159 return 0;
2160}
2161
2162#endif /* RT_OS_WINDOWS */
2163
2164/**
2165 * Sends a signal to the client watcher thread to rescan the set of machines
2166 * that have open sessions.
2167 *
2168 * @note Doesn't lock anything.
2169 */
2170void VirtualBox::updateClientWatcher()
2171{
2172 AutoCaller autoCaller(this);
2173 AssertComRCReturnVoid(autoCaller.rc());
2174
2175 AssertReturnVoid(m->threadClientWatcher != NIL_RTTHREAD);
2176
2177 /* sent an update request */
2178#if defined(RT_OS_WINDOWS)
2179 ::SetEvent(m->updateReq);
2180#elif defined(RT_OS_OS2)
2181 RTSemEventSignal(m->updateReq);
2182#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
2183 RTSemEventSignal(m->updateReq);
2184#else
2185# error "Port me!"
2186#endif
2187}
2188
2189/**
2190 * Adds the given child process ID to the list of processes to be reaped.
2191 * This call should be followed by #updateClientWatcher() to take the effect.
2192 */
2193void VirtualBox::addProcessToReap(RTPROCESS pid)
2194{
2195 AutoCaller autoCaller(this);
2196 AssertComRCReturnVoid(autoCaller.rc());
2197
2198 /// @todo (dmik) Win32?
2199#ifndef RT_OS_WINDOWS
2200 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2201 m->llProcesses.push_back(pid);
2202#endif
2203}
2204
2205/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2206struct MachineEvent : public VirtualBox::CallbackEvent
2207{
2208 MachineEvent(VirtualBox *aVB, const Guid &aId)
2209 : CallbackEvent(aVB, VirtualBoxCallbackRegistration::kOnMachineDataChanged), id(aId.toUtf16())
2210 {}
2211
2212 MachineEvent(VirtualBox *aVB, const Guid &aId, MachineState_T aState)
2213 : CallbackEvent(aVB, VirtualBoxCallbackRegistration::kOnMachineStateChanged), id(aId.toUtf16())
2214 , state(aState)
2215 {}
2216
2217 MachineEvent(VirtualBox *aVB, const Guid &aId, BOOL aRegistered)
2218 : CallbackEvent(aVB, VirtualBoxCallbackRegistration::kOnMachineRegistered), id(aId.toUtf16())
2219 , registered(aRegistered)
2220 {}
2221
2222 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2223 {
2224 switch (mWhat)
2225 {
2226 case VirtualBoxCallbackRegistration::kOnMachineDataChanged:
2227 aEvDesc.init(aSource, VBoxEventType_OnMachineDataChanged, id.raw());
2228 break;
2229
2230 case VirtualBoxCallbackRegistration::kOnMachineStateChanged:
2231 aEvDesc.init(aSource, VBoxEventType_OnMachineStateChanged, id.raw(), state);
2232 break;
2233
2234 case VirtualBoxCallbackRegistration::kOnMachineRegistered:
2235 aEvDesc.init(aSource, VBoxEventType_OnMachineRegistered, id.raw(), registered);
2236 break;
2237
2238 default:
2239 AssertFailedReturn(S_OK);
2240 }
2241 return S_OK;
2242 }
2243
2244 Bstr id;
2245 MachineState_T state;
2246 BOOL registered;
2247};
2248
2249/**
2250 * @note Doesn't lock any object.
2251 */
2252void VirtualBox::onMachineStateChange(const Guid &aId, MachineState_T aState)
2253{
2254 postEvent(new MachineEvent(this, aId, aState));
2255}
2256
2257/**
2258 * @note Doesn't lock any object.
2259 */
2260void VirtualBox::onMachineDataChange(const Guid &aId)
2261{
2262 postEvent(new MachineEvent(this, aId));
2263}
2264
2265/**
2266 * @note Locks this object for reading.
2267 */
2268BOOL VirtualBox::onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
2269 Bstr &aError)
2270{
2271 LogFlowThisFunc(("machine={%s} aKey={%ls} aValue={%ls}\n",
2272 aId.toString().c_str(), aKey, aValue));
2273
2274 AutoCaller autoCaller(this);
2275 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2276
2277 BOOL allowChange = TRUE;
2278 Bstr id = aId.toUtf16();
2279
2280 VBoxEventDesc evDesc;
2281 evDesc.init(m->pEventSource, VBoxEventType_OnExtraDataCanChange, id.raw(), aKey, aValue);
2282 BOOL fDelivered = evDesc.fire(3000); /* Wait up to 3 secs for delivery */
2283 //Assert(fDelivered);
2284 if (fDelivered)
2285 {
2286 ComPtr<IEvent> aEvent;
2287 evDesc.getEvent(aEvent.asOutParam());
2288 ComPtr<IExtraDataCanChangeEvent> aCanChangeEvent = aEvent;
2289 Assert(aCanChangeEvent);
2290 BOOL fVetoed = FALSE;
2291 aCanChangeEvent->IsVetoed(&fVetoed);
2292 allowChange = !fVetoed;
2293
2294 if (!allowChange)
2295 {
2296 SafeArray<BSTR> aVetos;
2297 aCanChangeEvent->GetVetos(ComSafeArrayAsOutParam(aVetos));
2298 if (aVetos.size() > 0)
2299 aError = aVetos[0];
2300 }
2301 }
2302 else
2303 allowChange = TRUE;
2304
2305 LogFlowThisFunc(("allowChange=%RTbool\n", allowChange));
2306 return allowChange;
2307}
2308
2309/** Event for onExtraDataChange() */
2310struct ExtraDataEvent : public VirtualBox::CallbackEvent
2311{
2312 ExtraDataEvent(VirtualBox *aVB, const Guid &aMachineId,
2313 IN_BSTR aKey, IN_BSTR aVal)
2314 : CallbackEvent(aVB, VirtualBoxCallbackRegistration::kOnExtraDataChanged)
2315 , machineId(aMachineId.toUtf16()), key(aKey), val(aVal)
2316 {}
2317
2318 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2319 {
2320 return aEvDesc.init(aSource, VBoxEventType_OnExtraDataChanged, machineId.raw(), key.raw(), val.raw());
2321 }
2322
2323 Bstr machineId, key, val;
2324};
2325
2326/**
2327 * @note Doesn't lock any object.
2328 */
2329void VirtualBox::onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue)
2330{
2331 postEvent(new ExtraDataEvent(this, aId, aKey, aValue));
2332}
2333
2334/**
2335 * @note Doesn't lock any object.
2336 */
2337void VirtualBox::onMachineRegistered(const Guid &aId, BOOL aRegistered)
2338{
2339 postEvent(new MachineEvent(this, aId, aRegistered));
2340}
2341
2342/** Event for onSessionStateChange() */
2343struct SessionEvent : public VirtualBox::CallbackEvent
2344{
2345 SessionEvent(VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2346 : CallbackEvent(aVB, VirtualBoxCallbackRegistration::kOnSessionStateChanged)
2347 , machineId(aMachineId.toUtf16()), sessionState(aState)
2348 {}
2349
2350 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2351 {
2352 return aEvDesc.init(aSource, VBoxEventType_OnSessionStateChanged, machineId.raw(), sessionState);
2353 }
2354 Bstr machineId;
2355 SessionState_T sessionState;
2356};
2357
2358/**
2359 * @note Doesn't lock any object.
2360 */
2361void VirtualBox::onSessionStateChange(const Guid &aId, SessionState_T aState)
2362{
2363 postEvent(new SessionEvent(this, aId, aState));
2364}
2365
2366/** Event for onSnapshotTaken(), onSnapshotDeleted() and onSnapshotChange() */
2367struct SnapshotEvent : public VirtualBox::CallbackEvent
2368{
2369 SnapshotEvent(VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2370 VirtualBoxCallbackRegistration::CallbackBit aWhat)
2371 : CallbackEvent(aVB, aWhat)
2372 , machineId(aMachineId), snapshotId(aSnapshotId)
2373 {}
2374
2375 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2376 {
2377 return aEvDesc.init(aSource, VBoxEventType_OnSnapshotTaken,
2378 machineId.toUtf16().raw(), snapshotId.toUtf16().raw());
2379 }
2380
2381 Guid machineId;
2382 Guid snapshotId;
2383};
2384
2385/**
2386 * @note Doesn't lock any object.
2387 */
2388void VirtualBox::onSnapshotTaken(const Guid &aMachineId, const Guid &aSnapshotId)
2389{
2390 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2391 VirtualBoxCallbackRegistration::kOnSnapshotTaken));
2392}
2393
2394/**
2395 * @note Doesn't lock any object.
2396 */
2397void VirtualBox::onSnapshotDeleted(const Guid &aMachineId, const Guid &aSnapshotId)
2398{
2399 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2400 VirtualBoxCallbackRegistration::kOnSnapshotDeleted));
2401}
2402
2403/**
2404 * @note Doesn't lock any object.
2405 */
2406void VirtualBox::onSnapshotChange(const Guid &aMachineId, const Guid &aSnapshotId)
2407{
2408 postEvent(new SnapshotEvent(this, aMachineId, aSnapshotId,
2409 VirtualBoxCallbackRegistration::kOnSnapshotChanged));
2410}
2411
2412/** Event for onGuestPropertyChange() */
2413struct GuestPropertyEvent : public VirtualBox::CallbackEvent
2414{
2415 GuestPropertyEvent(VirtualBox *aVBox, const Guid &aMachineId,
2416 IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
2417 : CallbackEvent(aVBox, VirtualBoxCallbackRegistration::kOnGuestPropertyChanged),
2418 machineId(aMachineId),
2419 name(aName),
2420 value(aValue),
2421 flags(aFlags)
2422 {}
2423
2424 virtual HRESULT prepareEventDesc(IEventSource* aSource, VBoxEventDesc& aEvDesc)
2425 {
2426 return aEvDesc.init(aSource, VBoxEventType_OnGuestPropertyChanged,
2427 machineId.toUtf16().raw(), name.raw(), value.raw(), flags.raw());
2428 }
2429
2430 Guid machineId;
2431 Bstr name, value, flags;
2432};
2433
2434/**
2435 * @note Doesn't lock any object.
2436 */
2437void VirtualBox::onGuestPropertyChange(const Guid &aMachineId, IN_BSTR aName,
2438 IN_BSTR aValue, IN_BSTR aFlags)
2439{
2440 postEvent(new GuestPropertyEvent(this, aMachineId, aName, aValue, aFlags));
2441}
2442
2443/** Event for onMachineUninit(), this is not a CallbackEvent */
2444class MachineUninitEvent : public Event
2445{
2446public:
2447
2448 MachineUninitEvent(VirtualBox *aVirtualBox, Machine *aMachine)
2449 : mVirtualBox(aVirtualBox), mMachine(aMachine)
2450 {
2451 Assert(aVirtualBox);
2452 Assert(aMachine);
2453 }
2454
2455 void *handler()
2456 {
2457#ifdef VBOX_WITH_RESOURCE_USAGE_API
2458 /* Handle unregistering metrics here, as it is not vital to get
2459 * it done immediately. It reduces the number of locks needed and
2460 * the lock contention in SessionMachine::uninit. */
2461 {
2462 AutoWriteLock mLock(mMachine COMMA_LOCKVAL_SRC_POS);
2463 mMachine->unregisterMetrics(mVirtualBox->performanceCollector(), mMachine);
2464 }
2465#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2466
2467 return NULL;
2468 }
2469
2470private:
2471
2472 /**
2473 * Note that this is a weak ref -- the CallbackEvent handler thread
2474 * is bound to the lifetime of the VirtualBox instance, so it's safe.
2475 */
2476 VirtualBox *mVirtualBox;
2477
2478 /** Reference to the machine object. */
2479 ComObjPtr<Machine> mMachine;
2480};
2481
2482/**
2483 * Trigger internal event. This isn't meant to be signalled to clients.
2484 * @note Doesn't lock any object.
2485 */
2486void VirtualBox::onMachineUninit(Machine *aMachine)
2487{
2488 postEvent(new MachineUninitEvent(this, aMachine));
2489}
2490
2491/**
2492 * @note Doesn't lock any object.
2493 */
2494void VirtualBox::onNatRedirectChange(const Guid &aMachineId, ULONG ulSlot, bool fRemove, IN_BSTR aName,
2495 NATProtocol_T aProto, IN_BSTR aHostIp, uint16_t aHostPort,
2496 IN_BSTR aGuestIp, uint16_t aGuestPort)
2497{
2498 fireNATRedirectEvent(m->pEventSource, aMachineId.toUtf16().raw(), ulSlot, fRemove, aName, aProto, aHostIp,
2499 aHostPort, aGuestIp, aGuestPort);
2500}
2501
2502/**
2503 * @note Locks this object for reading.
2504 */
2505ComObjPtr<GuestOSType> VirtualBox::getUnknownOSType()
2506{
2507 ComObjPtr<GuestOSType> type;
2508 AutoCaller autoCaller(this);
2509 AssertComRCReturn(autoCaller.rc(), type);
2510
2511 /* unknown type must always be the first */
2512 ComAssertRet(m->allGuestOSTypes.size() > 0, type);
2513
2514 return m->allGuestOSTypes.front();
2515}
2516
2517/**
2518 * Returns the list of opened machines (machines having direct sessions opened
2519 * by client processes) and optionally the list of direct session controls.
2520 *
2521 * @param aMachines Where to put opened machines (will be empty if none).
2522 * @param aControls Where to put direct session controls (optional).
2523 *
2524 * @note The returned lists contain smart pointers. So, clear it as soon as
2525 * it becomes no more necessary to release instances.
2526 *
2527 * @note It can be possible that a session machine from the list has been
2528 * already uninitialized, so do a usual AutoCaller/AutoReadLock sequence
2529 * when accessing unprotected data directly.
2530 *
2531 * @note Locks objects for reading.
2532 */
2533void VirtualBox::getOpenedMachines(SessionMachinesList &aMachines,
2534 InternalControlList *aControls /*= NULL*/)
2535{
2536 AutoCaller autoCaller(this);
2537 AssertComRCReturnVoid(autoCaller.rc());
2538
2539 aMachines.clear();
2540 if (aControls)
2541 aControls->clear();
2542
2543 AutoReadLock alock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2544
2545 for (MachinesOList::iterator it = m->allMachines.begin();
2546 it != m->allMachines.end();
2547 ++it)
2548 {
2549 ComObjPtr<SessionMachine> sm;
2550 ComPtr<IInternalSessionControl> ctl;
2551 if ((*it)->isSessionOpen(sm, &ctl))
2552 {
2553 aMachines.push_back(sm);
2554 if (aControls)
2555 aControls->push_back(ctl);
2556 }
2557 }
2558}
2559
2560/**
2561 * Searches for a machine object with the given ID in the collection
2562 * of registered machines.
2563 *
2564 * @param aId Machine UUID to look for.
2565 * @param aPermitInaccessible If true, inaccessible machines will be found;
2566 * if false, this will fail if the given machine is inaccessible.
2567 * @param aSetError If true, set errorinfo if the machine is not found.
2568 * @param aMachine Returned machine, if found.
2569 * @return
2570 */
2571HRESULT VirtualBox::findMachine(const Guid &aId,
2572 bool fPermitInaccessible,
2573 bool aSetError,
2574 ComObjPtr<Machine> *aMachine /* = NULL */)
2575{
2576 HRESULT rc = VBOX_E_OBJECT_NOT_FOUND;
2577
2578 AutoCaller autoCaller(this);
2579 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2580
2581 {
2582 AutoReadLock al(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2583
2584 for (MachinesOList::iterator it = m->allMachines.begin();
2585 it != m->allMachines.end();
2586 ++it)
2587 {
2588 ComObjPtr<Machine> pMachine2 = *it;
2589
2590 if (!fPermitInaccessible)
2591 {
2592 // skip inaccessible machines
2593 AutoCaller machCaller(pMachine2);
2594 if (FAILED(machCaller.rc()))
2595 continue;
2596 }
2597
2598 if (pMachine2->getId() == aId)
2599 {
2600 rc = S_OK;
2601 if (aMachine)
2602 *aMachine = pMachine2;
2603 break;
2604 }
2605 }
2606 }
2607
2608 if (aSetError && FAILED(rc))
2609 rc = setError(rc,
2610 tr("Could not find a registered machine with UUID {%RTuuid}"),
2611 aId.raw());
2612
2613 return rc;
2614}
2615
2616/**
2617 * Searches for a Medium object with the given ID in the list of registered
2618 * hard disks.
2619 *
2620 * @param aId ID of the hard disk. Must not be empty.
2621 * @param aSetError If @c true , the appropriate error info is set in case
2622 * when the hard disk is not found.
2623 * @param aHardDisk Where to store the found hard disk object (can be NULL).
2624 *
2625 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2626 *
2627 * @note Locks the media tree for reading.
2628 */
2629HRESULT VirtualBox::findHardDiskById(const Guid &id,
2630 bool aSetError,
2631 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
2632{
2633 AssertReturn(!id.isEmpty(), E_INVALIDARG);
2634
2635 // we use the hard disks map, but it is protected by the
2636 // hard disk _list_ lock handle
2637 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2638
2639 HardDiskMap::const_iterator it = m->mapHardDisks.find(id);
2640 if (it != m->mapHardDisks.end())
2641 {
2642 if (aHardDisk)
2643 *aHardDisk = (*it).second;
2644 return S_OK;
2645 }
2646
2647 if (aSetError)
2648 return setError(VBOX_E_OBJECT_NOT_FOUND,
2649 tr("Could not find an open hard disk with UUID {%RTuuid}"),
2650 id.raw());
2651
2652 return VBOX_E_OBJECT_NOT_FOUND;
2653}
2654
2655/**
2656 * Searches for a Medium object with the given ID or location in the list of
2657 * registered hard disks. If both ID and location are specified, the first
2658 * object that matches either of them (not necessarily both) is returned.
2659 *
2660 * @param aLocation Full location specification. Must not be empty.
2661 * @param aSetError If @c true , the appropriate error info is set in case
2662 * when the hard disk is not found.
2663 * @param aHardDisk Where to store the found hard disk object (can be NULL).
2664 *
2665 * @return S_OK, E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2666 *
2667 * @note Locks the media tree for reading.
2668 */
2669HRESULT VirtualBox::findHardDiskByLocation(const Utf8Str &strLocation,
2670 bool aSetError,
2671 ComObjPtr<Medium> *aHardDisk /*= NULL*/)
2672{
2673 AssertReturn(!strLocation.isEmpty(), E_INVALIDARG);
2674
2675 // we use the hard disks map, but it is protected by the
2676 // hard disk _list_ lock handle
2677 AutoReadLock alock(m->allHardDisks.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2678
2679 for (HardDiskMap::const_iterator it = m->mapHardDisks.begin();
2680 it != m->mapHardDisks.end();
2681 ++it)
2682 {
2683 const ComObjPtr<Medium> &pHD = (*it).second;
2684
2685 AutoCaller autoCaller(pHD);
2686 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2687 AutoWriteLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2688
2689 Utf8Str strLocationFull = pHD->getLocationFull();
2690
2691 if (0 == RTPathCompare(strLocationFull.c_str(), strLocation.c_str()))
2692 {
2693 if (aHardDisk)
2694 *aHardDisk = pHD;
2695 return S_OK;
2696 }
2697 }
2698
2699 if (aSetError)
2700 return setError(VBOX_E_OBJECT_NOT_FOUND,
2701 tr("Could not find an open hard disk with location '%s'"),
2702 strLocation.c_str());
2703
2704 return VBOX_E_OBJECT_NOT_FOUND;
2705}
2706
2707/**
2708 * Searches for a Medium object with the given ID or location in the list of
2709 * registered DVD or floppy images, depending on the @a mediumType argument.
2710 * If both ID and file path are specified, the first object that matches either
2711 * of them (not necessarily both) is returned.
2712 *
2713 * @param mediumType Must be either DeviceType_DVD or DeviceType_Floppy.
2714 * @param aId ID of the image file (unused when NULL).
2715 * @param aLocation Full path to the image file (unused when NULL).
2716 * @param aSetError If @c true, the appropriate error info is set in case when
2717 * the image is not found.
2718 * @param aImage Where to store the found image object (can be NULL).
2719 *
2720 * @return S_OK when found or E_INVALIDARG or VBOX_E_OBJECT_NOT_FOUND when not found.
2721 *
2722 * @note Locks the media tree for reading.
2723 */
2724HRESULT VirtualBox::findDVDOrFloppyImage(DeviceType_T mediumType,
2725 const Guid *aId,
2726 const Utf8Str &aLocation,
2727 bool aSetError,
2728 ComObjPtr<Medium> *aImage /* = NULL */)
2729{
2730 AssertReturn(aId || !aLocation.isEmpty(), E_INVALIDARG);
2731
2732 Utf8Str location;
2733 if (!aLocation.isEmpty())
2734 {
2735 int vrc = calculateFullPath(aLocation, location);
2736 if (RT_FAILURE(vrc))
2737 return setError(VBOX_E_FILE_ERROR,
2738 tr("Invalid image file location '%ls' (%Rrc)"),
2739 aLocation.c_str(),
2740 vrc);
2741 }
2742
2743 MediaOList *pMediaList;
2744
2745 switch (mediumType)
2746 {
2747 case DeviceType_DVD:
2748 pMediaList = &m->allDVDImages;
2749 break;
2750
2751 case DeviceType_Floppy:
2752 pMediaList = &m->allFloppyImages;
2753 break;
2754
2755 default:
2756 return E_INVALIDARG;
2757 }
2758
2759 AutoReadLock alock(pMediaList->getLockHandle() COMMA_LOCKVAL_SRC_POS);
2760
2761 bool found = false;
2762
2763 for (MediaList::const_iterator it = pMediaList->begin();
2764 it != pMediaList->end();
2765 ++it)
2766 {
2767 // no AutoCaller, registered image life time is bound to this
2768 Medium *pMedium = *it;
2769 AutoReadLock imageLock(pMedium COMMA_LOCKVAL_SRC_POS);
2770 const Utf8Str &strLocationFull = pMedium->getLocationFull();
2771
2772 found = ( aId
2773 && pMedium->getId() == *aId)
2774 || ( !aLocation.isEmpty()
2775 && RTPathCompare(location.c_str(),
2776 strLocationFull.c_str()) == 0);
2777 if (found)
2778 {
2779 if (pMedium->getDeviceType() != mediumType)
2780 {
2781 if (mediumType == DeviceType_DVD)
2782 return setError(E_INVALIDARG,
2783 "Cannot mount DVD medium '%s' as floppy", strLocationFull.c_str());
2784 else
2785 return setError(E_INVALIDARG,
2786 "Cannot mount floppy medium '%s' as DVD", strLocationFull.c_str());
2787 }
2788
2789 if (aImage)
2790 *aImage = pMedium;
2791 break;
2792 }
2793 }
2794
2795 HRESULT rc = found ? S_OK : VBOX_E_OBJECT_NOT_FOUND;
2796
2797 if (aSetError && !found)
2798 {
2799 if (aId)
2800 setError(rc,
2801 tr("Could not find an image file with UUID {%RTuuid} in the media registry ('%s')"),
2802 aId->raw(),
2803 m->strSettingsFilePath.c_str());
2804 else
2805 setError(rc,
2806 tr("Could not find an image file with location '%ls' in the media registry ('%s')"),
2807 aLocation.c_str(),
2808 m->strSettingsFilePath.c_str());
2809 }
2810
2811 return rc;
2812}
2813
2814/**
2815 * Searches for an IMedium object that represents the given UUID.
2816 *
2817 * If the UUID is empty (indicating an empty drive), this sets pMedium
2818 * to NULL and returns S_OK.
2819 *
2820 * If the UUID refers to a host drive of the given device type, this
2821 * sets pMedium to the object from the list in IHost and returns S_OK.
2822 *
2823 * If the UUID is an image file, this sets pMedium to the object that
2824 * findDVDOrFloppyImage() returned.
2825 *
2826 * If none of the above apply, this returns VBOX_E_OBJECT_NOT_FOUND.
2827 *
2828 * @param mediumType Must be DeviceType_DVD or DeviceType_Floppy.
2829 * @param uuid UUID to search for; must refer to a host drive or an image file or be null.
2830 * @param fRefresh Whether to refresh the list of host drives in IHost (see Host::getDrives())
2831 * @param pMedium out: IMedium object found.
2832 * @return
2833 */
2834HRESULT VirtualBox::findRemoveableMedium(DeviceType_T mediumType,
2835 const Guid &uuid,
2836 bool fRefresh,
2837 ComObjPtr<Medium> &pMedium)
2838{
2839 if (uuid.isEmpty())
2840 {
2841 // that's easy
2842 pMedium.setNull();
2843 return S_OK;
2844 }
2845
2846 // first search for host drive with that UUID
2847 HRESULT rc = m->pHost->findHostDriveById(mediumType,
2848 uuid,
2849 fRefresh,
2850 pMedium);
2851 if (rc == VBOX_E_OBJECT_NOT_FOUND)
2852 // then search for an image with that UUID
2853 rc = findDVDOrFloppyImage(mediumType, &uuid, Utf8Str::Empty, true /* aSetError */, &pMedium);
2854
2855 return rc;
2856}
2857
2858HRESULT VirtualBox::findGuestOSType(const Bstr &bstrOSType,
2859 GuestOSType*& pGuestOSType)
2860{
2861 /* Look for a GuestOSType object */
2862 AssertMsg(m->allGuestOSTypes.size() != 0,
2863 ("Guest OS types array must be filled"));
2864
2865 if (bstrOSType.isEmpty())
2866 {
2867 pGuestOSType = NULL;
2868 return S_OK;
2869 }
2870
2871 AutoReadLock alock(m->allGuestOSTypes.getLockHandle() COMMA_LOCKVAL_SRC_POS);
2872 for (GuestOSTypesOList::const_iterator it = m->allGuestOSTypes.begin();
2873 it != m->allGuestOSTypes.end();
2874 ++it)
2875 {
2876 if ((*it)->id() == bstrOSType)
2877 {
2878 pGuestOSType = *it;
2879 return S_OK;
2880 }
2881 }
2882
2883 return setError(VBOX_E_OBJECT_NOT_FOUND,
2884 tr("Guest OS type '%ls' is invalid"),
2885 bstrOSType.raw());
2886}
2887
2888/**
2889 * Returns the constant pseudo-machine UUID that is used to identify the
2890 * global media registry.
2891 *
2892 * Starting with VirtualBox 4.0 each medium remembers in its instance data
2893 * in which media registry it is saved (if any): this can either be a machine
2894 * UUID, if it's in a per-machine media registry, or this global ID.
2895 *
2896 * This UUID is only used to identify the VirtualBox object while VirtualBox
2897 * is running. It is a compile-time constant and not saved anywhere.
2898 *
2899 * @return
2900 */
2901const Guid& VirtualBox::getGlobalRegistryId() const
2902{
2903 return m->uuidMediaRegistry;
2904}
2905
2906const ComObjPtr<Host>& VirtualBox::host() const
2907{
2908 return m->pHost;
2909}
2910
2911SystemProperties* VirtualBox::getSystemProperties() const
2912{
2913 return m->pSystemProperties;
2914}
2915
2916#ifdef VBOX_WITH_EXTPACK
2917/**
2918 * Getter that SystemProperties and others can use to talk to the extension
2919 * pack manager.
2920 */
2921ExtPackManager* VirtualBox::getExtPackManager() const
2922{
2923 return m->ptrExtPackManager;
2924}
2925#endif
2926
2927#ifdef VBOX_WITH_RESOURCE_USAGE_API
2928const ComObjPtr<PerformanceCollector>& VirtualBox::performanceCollector() const
2929{
2930 return m->pPerformanceCollector;
2931}
2932#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2933
2934/**
2935 * Returns the default machine folder from the system properties
2936 * with proper locking.
2937 * @return
2938 */
2939void VirtualBox::getDefaultMachineFolder(Utf8Str &str) const
2940{
2941 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
2942 str = m->pSystemProperties->m->strDefaultMachineFolder;
2943}
2944
2945/**
2946 * Returns the default hard disk format from the system properties
2947 * with proper locking.
2948 * @return
2949 */
2950void VirtualBox::getDefaultHardDiskFormat(Utf8Str &str) const
2951{
2952 AutoReadLock propsLock(m->pSystemProperties COMMA_LOCKVAL_SRC_POS);
2953 str = m->pSystemProperties->m->strDefaultHardDiskFormat;
2954}
2955
2956const Utf8Str& VirtualBox::homeDir() const
2957{
2958 return m->strHomeDir;
2959}
2960
2961/**
2962 * Calculates the absolute path of the given path taking the VirtualBox home
2963 * directory as the current directory.
2964 *
2965 * @param aPath Path to calculate the absolute path for.
2966 * @param aResult Where to put the result (used only on success, can be the
2967 * same Utf8Str instance as passed in @a aPath).
2968 * @return IPRT result.
2969 *
2970 * @note Doesn't lock any object.
2971 */
2972int VirtualBox::calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult)
2973{
2974 AutoCaller autoCaller(this);
2975 AssertComRCReturn(autoCaller.rc(), VERR_GENERAL_FAILURE);
2976
2977 /* no need to lock since mHomeDir is const */
2978
2979 char folder[RTPATH_MAX];
2980 int vrc = RTPathAbsEx(m->strHomeDir.c_str(),
2981 strPath.c_str(),
2982 folder,
2983 sizeof(folder));
2984 if (RT_SUCCESS(vrc))
2985 aResult = folder;
2986
2987 return vrc;
2988}
2989
2990/**
2991 * Copies strSource to strTarget, making it relative to the VirtualBox config folder
2992 * if it is a subdirectory thereof, or simply copying it otherwise.
2993 *
2994 * @param strSource Path to evalue and copy.
2995 * @param strTarget Buffer to receive target path.
2996 */
2997void VirtualBox::copyPathRelativeToConfig(const Utf8Str &strSource,
2998 Utf8Str &strTarget)
2999{
3000 AutoCaller autoCaller(this);
3001 AssertComRCReturnVoid(autoCaller.rc());
3002
3003 // no need to lock since mHomeDir is const
3004
3005 // use strTarget as a temporary buffer to hold the machine settings dir
3006 strTarget = m->strHomeDir;
3007 if (RTPathStartsWith(strSource.c_str(), strTarget.c_str()))
3008 // is relative: then append what's left
3009 strTarget.append(strSource.c_str() + strTarget.length()); // include '/'
3010 else
3011 // is not relative: then overwrite
3012 strTarget = strSource;
3013}
3014
3015// private methods
3016/////////////////////////////////////////////////////////////////////////////
3017
3018/**
3019 * Checks if there is a hard disk, DVD or floppy image with the given ID or
3020 * location already registered.
3021 *
3022 * On return, sets @a aConflict to the string describing the conflicting medium,
3023 * or sets it to @c Null if no conflicting media is found. Returns S_OK in
3024 * either case. A failure is unexpected.
3025 *
3026 * @param aId UUID to check.
3027 * @param aLocation Location to check.
3028 * @param aConflict Where to return parameters of the conflicting medium.
3029 *
3030 * @note Locks the media tree and media objects for reading.
3031 */
3032HRESULT VirtualBox::checkMediaForConflicts(const Guid &aId,
3033 const Utf8Str &aLocation,
3034 Utf8Str &aConflict,
3035 bool &fIdentical)
3036{
3037 aConflict.setNull();
3038
3039 AssertReturn(!aId.isEmpty() && !aLocation.isEmpty(), E_FAIL);
3040
3041 AutoReadLock alock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3042
3043 HRESULT rc = S_OK;
3044
3045 aConflict.setNull();
3046 fIdentical = false;
3047
3048 ComObjPtr<Medium> pMediumFound;
3049 const char *pcszType = NULL;
3050
3051 if (!aId.isEmpty())
3052 rc = findHardDiskById(aId, false /* aSetError */, &pMediumFound);
3053 if (FAILED(rc) && !aLocation.isEmpty())
3054 rc = findHardDiskByLocation(aLocation, false /* aSetError */, &pMediumFound);
3055 if (SUCCEEDED(rc))
3056 pcszType = tr("hard disk");
3057
3058 if (!pcszType)
3059 {
3060 rc = findDVDOrFloppyImage(DeviceType_DVD, &aId, aLocation, false /* aSetError */, &pMediumFound);
3061 if (SUCCEEDED(rc))
3062 pcszType = tr("CD/DVD image");
3063 }
3064
3065 if (!pcszType)
3066 {
3067 rc = findDVDOrFloppyImage(DeviceType_Floppy, &aId, aLocation, false /* aSetError */, &pMediumFound);
3068 if (SUCCEEDED(rc))
3069 pcszType = tr("floppy image");
3070 }
3071
3072 if (pcszType && pMediumFound)
3073 {
3074 /* Note: no AutoCaller since bound to this */
3075 AutoReadLock mlock(pMediumFound COMMA_LOCKVAL_SRC_POS);
3076
3077 Utf8Str strLocFound = pMediumFound->getLocationFull();
3078 Guid idFound = pMediumFound->getId();
3079
3080 if ( (strLocFound == aLocation)
3081 && (idFound == aId)
3082 )
3083 fIdentical = true;
3084
3085 aConflict = Utf8StrFmt(tr("%s '%s' with UUID {%RTuuid}"),
3086 pcszType,
3087 strLocFound.c_str(),
3088 idFound.raw());
3089 }
3090
3091 return S_OK;
3092}
3093
3094/**
3095 * Called from Machine::prepareSaveSettings() when it has detected
3096 * that a machine has been renamed. Such renames will require
3097 * updating the global media registry during the
3098 * VirtualBox::saveSettings() that follows later.
3099*
3100 * When a machine is renamed, there may well be media (in particular,
3101 * diff images for snapshots) in the global registry that will need
3102 * to have their paths updated. Before 3.2, Machine::saveSettings
3103 * used to call VirtualBox::saveSettings implicitly, which was both
3104 * unintuitive and caused locking order problems. Now, we remember
3105 * such pending name changes with this method so that
3106 * VirtualBox::saveSettings() can process them properly.
3107 */
3108void VirtualBox::rememberMachineNameChangeForMedia(const Utf8Str &strOldConfigDir,
3109 const Utf8Str &strNewConfigDir)
3110{
3111 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3112
3113 Data::PendingMachineRename pmr;
3114 pmr.strConfigDirOld = strOldConfigDir;
3115 pmr.strConfigDirNew = strNewConfigDir;
3116 m->llPendingMachineRenames.push_back(pmr);
3117}
3118
3119/**
3120 * Goes through all known media (hard disks, floppies and DVDs) and saves
3121 * those into the given settings::MediaRegistry structures whose registry
3122 * ID match the given UUID.
3123 *
3124 * Before actually writing to the structures, all media paths (not just the
3125 * ones for the given registry) are updated if machines have been renamed
3126 * since the last call.
3127 *
3128 * This gets called from two contexts:
3129 *
3130 * -- VirtualBox::saveSettings() with the UUID of the global registry
3131 * (VirtualBox::Data.uuidRegistry); this will save those media
3132 * which had been loaded from the global registry or have been
3133 * attached to a "legacy" machine which can't save its own registry;
3134 *
3135 * -- Machine::saveSettings() with the UUID of a machine, if a medium
3136 * has been attached to a machine created with VirtualBox 4.0 or later.
3137 *
3138 * Media which have only been temporarily opened without having been
3139 * attached to a machine have a NULL registry UUID and therefore don't
3140 * get saved.
3141 *
3142 * This locks the media tree. Throws HRESULT on errors!
3143 *
3144 * @param mediaRegistry Settings structure to fill.
3145 * @param uuidRegistry The UUID of the media registry; either a machine UUID (if machine registry) or the UUID of the global registry.
3146 * @param hardDiskFolder The machine folder for relative paths, if machine registry, or an empty string otherwise.
3147 */
3148void VirtualBox::saveMediaRegistry(settings::MediaRegistry &mediaRegistry,
3149 const Guid &uuidRegistry,
3150 const Utf8Str &strMachineFolder)
3151{
3152 // lock all media for the following; use a write lock because we're
3153 // modifying the PendingMachineRenamesList, which is protected by this
3154 AutoWriteLock mediaLock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3155
3156 // if a machine was renamed, then we'll need to refresh media paths
3157 if (m->llPendingMachineRenames.size())
3158 {
3159 // make a single list from the three media lists so we don't need three loops
3160 MediaList llAllMedia;
3161 // with hard disks, we must use the map, not the list, because the list only has base images
3162 for (HardDiskMap::iterator it = m->mapHardDisks.begin(); it != m->mapHardDisks.end(); ++it)
3163 llAllMedia.push_back(it->second);
3164 for (MediaList::iterator it = m->allDVDImages.begin(); it != m->allDVDImages.end(); ++it)
3165 llAllMedia.push_back(*it);
3166 for (MediaList::iterator it = m->allFloppyImages.begin(); it != m->allFloppyImages.end(); ++it)
3167 llAllMedia.push_back(*it);
3168
3169 for (MediaList::iterator it = llAllMedia.begin();
3170 it != llAllMedia.end();
3171 ++it)
3172 {
3173 Medium *pMedium = *it;
3174 for (Data::PendingMachineRenamesList::iterator it2 = m->llPendingMachineRenames.begin();
3175 it2 != m->llPendingMachineRenames.end();
3176 ++it2)
3177 {
3178 const Data::PendingMachineRename &pmr = *it2;
3179 pMedium->updatePath(pmr.strConfigDirOld,
3180 pmr.strConfigDirNew);
3181 }
3182 }
3183 // done, don't do it again until we have more machine renames
3184 m->llPendingMachineRenames.clear();
3185 }
3186
3187 HRESULT rc;
3188 // hard disks
3189 mediaRegistry.llHardDisks.clear();
3190 for (MediaList::const_iterator it = m->allHardDisks.begin();
3191 it != m->allHardDisks.end();
3192 ++it)
3193 {
3194 Medium *pMedium = *it;
3195 if (pMedium->isInRegistry(uuidRegistry))
3196 {
3197 settings::Medium med;
3198 rc = pMedium->saveSettings(med, strMachineFolder); // this recurses into its children
3199 if (FAILED(rc)) throw rc;
3200 mediaRegistry.llHardDisks.push_back(med);
3201 }
3202 }
3203
3204 // CD/DVD images
3205 mediaRegistry.llDvdImages.clear();
3206 for (MediaList::const_iterator it = m->allDVDImages.begin();
3207 it != m->allDVDImages.end();
3208 ++it)
3209 {
3210 Medium *pMedium = *it;
3211 if (pMedium->isInRegistry(uuidRegistry))
3212 {
3213 settings::Medium med;
3214 rc = pMedium->saveSettings(med, strMachineFolder);
3215 if (FAILED(rc)) throw rc;
3216 mediaRegistry.llDvdImages.push_back(med);
3217 }
3218 }
3219
3220 // floppy images
3221 mediaRegistry.llFloppyImages.clear();
3222 for (MediaList::const_iterator it = m->allFloppyImages.begin();
3223 it != m->allFloppyImages.end();
3224 ++it)
3225 {
3226 Medium *pMedium = *it;
3227 if (pMedium->isInRegistry(uuidRegistry))
3228 {
3229 settings::Medium med;
3230 rc = pMedium->saveSettings(med, strMachineFolder);
3231 if (FAILED(rc)) throw rc;
3232 mediaRegistry.llFloppyImages.push_back(med);
3233 }
3234 }
3235}
3236
3237/**
3238 * Helper function which actually writes out VirtualBox.xml, the main configuration file.
3239 * Gets called from the public VirtualBox::SaveSettings() as well as from various other
3240 * places internally when settings need saving.
3241 *
3242 * @note Caller must have locked the VirtualBox object for writing and must not hold any
3243 * other locks since this locks all kinds of member objects and trees temporarily,
3244 * which could cause conflicts.
3245 */
3246HRESULT VirtualBox::saveSettings()
3247{
3248 AutoCaller autoCaller(this);
3249 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3250
3251 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
3252 AssertReturn(!m->strSettingsFilePath.isEmpty(), E_FAIL);
3253
3254 HRESULT rc = S_OK;
3255
3256 try
3257 {
3258 // machines
3259 m->pMainConfigFile->llMachines.clear();
3260 {
3261 AutoReadLock machinesLock(m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3262 for (MachinesOList::iterator it = m->allMachines.begin();
3263 it != m->allMachines.end();
3264 ++it)
3265 {
3266 Machine *pMachine = *it;
3267 // save actual machine registry entry
3268 settings::MachineRegistryEntry mre;
3269 rc = pMachine->saveRegistryEntry(mre);
3270 m->pMainConfigFile->llMachines.push_back(mre);
3271 }
3272 }
3273
3274 saveMediaRegistry(m->pMainConfigFile->mediaRegistry,
3275 m->uuidMediaRegistry, // global media registry ID
3276 Utf8Str::Empty); // strMachineFolder
3277
3278 m->pMainConfigFile->llDhcpServers.clear();
3279 {
3280 AutoReadLock dhcpLock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3281 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
3282 it != m->allDHCPServers.end();
3283 ++it)
3284 {
3285 settings::DHCPServer d;
3286 rc = (*it)->saveSettings(d);
3287 if (FAILED(rc)) throw rc;
3288 m->pMainConfigFile->llDhcpServers.push_back(d);
3289 }
3290 }
3291
3292 // leave extra data alone, it's still in the config file
3293
3294 // host data (USB filters)
3295 rc = m->pHost->saveSettings(m->pMainConfigFile->host);
3296 if (FAILED(rc)) throw rc;
3297
3298 rc = m->pSystemProperties->saveSettings(m->pMainConfigFile->systemProperties);
3299 if (FAILED(rc)) throw rc;
3300
3301 // and write out the XML, still under the lock
3302 m->pMainConfigFile->write(m->strSettingsFilePath);
3303 }
3304 catch (HRESULT err)
3305 {
3306 /* we assume that error info is set by the thrower */
3307 rc = err;
3308 }
3309 catch (...)
3310 {
3311 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
3312 }
3313
3314 return rc;
3315}
3316
3317/**
3318 * Helper to register the machine.
3319 *
3320 * When called during VirtualBox startup, adds the given machine to the
3321 * collection of registered machines. Otherwise tries to mark the machine
3322 * as registered, and, if succeeded, adds it to the collection and
3323 * saves global settings.
3324 *
3325 * @note The caller must have added itself as a caller of the @a aMachine
3326 * object if calls this method not on VirtualBox startup.
3327 *
3328 * @param aMachine machine to register
3329 *
3330 * @note Locks objects!
3331 */
3332HRESULT VirtualBox::registerMachine(Machine *aMachine)
3333{
3334 ComAssertRet(aMachine, E_INVALIDARG);
3335
3336 AutoCaller autoCaller(this);
3337 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3338
3339 HRESULT rc = S_OK;
3340
3341 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3342
3343 {
3344 ComObjPtr<Machine> pMachine;
3345 rc = findMachine(aMachine->getId(),
3346 true /* fPermitInaccessible */,
3347 false /* aDoSetError */,
3348 &pMachine);
3349 if (SUCCEEDED(rc))
3350 {
3351 /* sanity */
3352 AutoLimitedCaller machCaller(pMachine);
3353 AssertComRC(machCaller.rc());
3354
3355 return setError(E_INVALIDARG,
3356 tr("Registered machine with UUID {%RTuuid} ('%s') already exists"),
3357 aMachine->getId().raw(),
3358 pMachine->getSettingsFileFull().c_str());
3359 }
3360
3361 ComAssertRet(rc == VBOX_E_OBJECT_NOT_FOUND, rc);
3362 rc = S_OK;
3363 }
3364
3365 if (autoCaller.state() != InInit)
3366 {
3367 rc = aMachine->prepareRegister();
3368 if (FAILED(rc)) return rc;
3369 }
3370
3371 /* add to the collection of registered machines */
3372 m->allMachines.addChild(aMachine);
3373
3374 if (autoCaller.state() != InInit)
3375 rc = saveSettings();
3376
3377 return rc;
3378}
3379
3380/**
3381 * Remembers the given hard disk by storing it in either the global hard disk registry
3382 * or a machine one.
3383 *
3384 * @note Caller must hold the media tree lock for writing; in addition, this locks @a aHardDisk for reading
3385 *
3386 * @param aHardDisk Hard disk object to remember.
3387 * @param uuidMachineRegistry UUID of machine whose registry should be used, or a NULL UUID for the global registry.
3388 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs of media registries that need saving.
3389 * @return
3390 */
3391HRESULT VirtualBox::registerHardDisk(Medium *pMedium,
3392 GuidList *pllRegistriesThatNeedSaving)
3393{
3394 AssertReturn(pMedium != NULL, E_INVALIDARG);
3395
3396 AutoCaller autoCaller(this);
3397 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3398
3399 AutoCaller hardDiskCaller(pMedium);
3400 AssertComRCReturn(hardDiskCaller.rc(), hardDiskCaller.rc());
3401
3402 // caller must hold the media tree write lock
3403 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3404
3405 Guid id;
3406 Utf8Str strLocationFull;
3407 ComObjPtr<Medium> pParent;
3408 {
3409 AutoReadLock hardDiskLock(pMedium COMMA_LOCKVAL_SRC_POS);
3410 id = pMedium->getId();
3411 strLocationFull = pMedium->getLocationFull();
3412 pParent = pMedium->getParent();
3413 }
3414
3415 HRESULT rc;
3416
3417 Utf8Str strConflict;
3418 bool fIdentical;
3419 rc = checkMediaForConflicts(id,
3420 strLocationFull,
3421 strConflict,
3422 fIdentical);
3423 if (FAILED(rc)) return rc;
3424
3425 if (!fIdentical)
3426 {
3427 if (strConflict.length())
3428 return setError(E_INVALIDARG,
3429 tr("Cannot register the hard disk '%s' {%RTuuid} because a %s already exists"),
3430 strLocationFull.c_str(),
3431 id.raw(),
3432 strConflict.c_str(),
3433 m->strSettingsFilePath.c_str());
3434
3435 // store base (root) hard disks in the list
3436 if (pParent.isNull())
3437 m->allHardDisks.getList().push_back(pMedium);
3438 // access the list directly because we already locked the list above
3439
3440 // store all hard disks (even differencing images) in the map
3441 m->mapHardDisks[id] = pMedium;
3442
3443 if (pllRegistriesThatNeedSaving)
3444 pMedium->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3445 }
3446
3447 return rc;
3448}
3449
3450/**
3451 * Removes the given hard disk from the hard disk registry.
3452 *
3453 * @param aHardDisk Hard disk object to remove.
3454 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3455 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3456 *
3457 * @note Caller must hold the media tree lock for writing; in addition, this locks @a aHardDisk for reading
3458 */
3459HRESULT VirtualBox::unregisterHardDisk(Medium *aHardDisk,
3460 GuidList *pllRegistriesThatNeedSaving)
3461{
3462 AssertReturn(aHardDisk != NULL, E_INVALIDARG);
3463
3464 AutoCaller autoCaller(this);
3465 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3466
3467 AutoCaller hardDiskCaller(aHardDisk);
3468 AssertComRCReturn(hardDiskCaller.rc(), hardDiskCaller.rc());
3469
3470 // caller must hold the media tree write lock
3471 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3472
3473 Guid id;
3474 ComObjPtr<Medium> pParent;
3475 {
3476 AutoReadLock hardDiskLock(aHardDisk COMMA_LOCKVAL_SRC_POS);
3477 id = aHardDisk->getId();
3478 pParent = aHardDisk->getParent();
3479 }
3480
3481 // remove base (root) hard disks from the list
3482 if (pParent.isNull())
3483 m->allHardDisks.getList().remove(aHardDisk);
3484 // access the list directly because caller must have locked the list
3485
3486 // remove all hard disks (even differencing images) from map
3487 size_t cnt = m->mapHardDisks.erase(id);
3488 Assert(cnt == 1);
3489 NOREF(cnt);
3490
3491 if (pllRegistriesThatNeedSaving)
3492 aHardDisk->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3493
3494 return S_OK;
3495}
3496
3497/**
3498 * Remembers the given image by storing it in the CD/DVD or floppy image registry.
3499 *
3500 * @param argImage Image object to remember.
3501 * @param argType Either DeviceType_DVD or DeviceType_Floppy.
3502 * @param uuidMachineRegistry UUID of machine whose registry should be used, or a NULL UUID for the global registry.
3503 *
3504 * @note Caller must hold the media tree lock for writing; in addition, this locks @a argImage for reading
3505 */
3506HRESULT VirtualBox::registerImage(Medium *pMedium,
3507 DeviceType_T argType,
3508 GuidList *pllRegistriesThatNeedSaving)
3509{
3510 AssertReturn(pMedium != NULL, E_INVALIDARG);
3511
3512 AutoCaller autoCaller(this);
3513 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3514
3515 AutoCaller imageCaller(pMedium);
3516 AssertComRCReturn(imageCaller.rc(), imageCaller.rc());
3517
3518 // caller must hold the media tree write lock
3519 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3520
3521 Guid id;
3522 Utf8Str strLocationFull;
3523 ComObjPtr<Medium> pParent;
3524 {
3525 AutoReadLock al(pMedium COMMA_LOCKVAL_SRC_POS);
3526 id = pMedium->getId();
3527 strLocationFull = pMedium->getLocationFull();
3528 pParent = pMedium->getParent();
3529 }
3530
3531 // work on DVDs or floppies list?
3532 ObjectsList<Medium> &all = (argType == DeviceType_DVD) ? m->allDVDImages : m->allFloppyImages;
3533
3534 HRESULT rc;
3535 // lock the images lists (list + map) while checking for conflicts
3536 AutoWriteLock al(all.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3537
3538 Utf8Str strConflict;
3539 bool fIdentical;
3540 rc = checkMediaForConflicts(id,
3541 strLocationFull,
3542 strConflict,
3543 fIdentical);
3544 if (FAILED(rc)) return rc;
3545
3546 if (!fIdentical)
3547 {
3548 if (strConflict.length())
3549 return setError(VBOX_E_INVALID_OBJECT_STATE,
3550 tr("Cannot register the image '%s' with UUID {%RTuuid} because a %s already exists"),
3551 strLocationFull.c_str(),
3552 id.raw(),
3553 strConflict.c_str());
3554
3555 // add to the collection
3556 all.getList().push_back(pMedium);
3557 // access the list directly because we already locked the list above
3558
3559 if (pllRegistriesThatNeedSaving)
3560 pMedium->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3561 }
3562
3563 return rc;
3564}
3565
3566/**
3567 * Removes the given image from the CD/DVD or floppy image registry.
3568 *
3569 * @param argImage Image object to remove.
3570 * @param argType Either DeviceType_DVD or DeviceType_Floppy.
3571 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3572 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3573 *
3574 * @note Caller must hold the media tree lock for writing; in addition, this locks @a argImage for reading
3575 */
3576HRESULT VirtualBox::unregisterImage(Medium *argImage,
3577 DeviceType_T argType,
3578 GuidList *pllRegistriesThatNeedSaving)
3579{
3580 AssertReturn(argImage != NULL, E_INVALIDARG);
3581
3582 AutoCaller autoCaller(this);
3583 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3584
3585 AutoCaller imageCaller(argImage);
3586 AssertComRCReturn(imageCaller.rc(), imageCaller.rc());
3587
3588 // caller must hold the media tree write lock
3589 Assert(getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3590
3591 Guid id;
3592 ComObjPtr<Medium> pParent;
3593 {
3594 AutoReadLock al(argImage COMMA_LOCKVAL_SRC_POS);
3595 id = argImage->getId();
3596 pParent = argImage->getParent();
3597 }
3598
3599 // work on DVDs or floppies list?
3600 ObjectsList<Medium> &all = (argType == DeviceType_DVD) ? m->allDVDImages : m->allFloppyImages;
3601
3602 // access the list directly because the caller must have requested the lock
3603 all.getList().remove(argImage);
3604
3605 HRESULT rc = S_OK;
3606
3607 if (pllRegistriesThatNeedSaving)
3608 argImage->addToRegistryIDList(*pllRegistriesThatNeedSaving);
3609
3610 return rc;
3611}
3612
3613/**
3614 * Little helper called from unregisterMachineMedia() to recursively add media to the given list,
3615 * with children appearing before their parents.
3616 * @param llMedia
3617 * @param pMedium
3618 */
3619void VirtualBox::pushMediumToListWithChildren(MediaList &llMedia, Medium *pMedium)
3620{
3621 // recurse first, then add ourselves; this way children end up on the
3622 // list before their parents
3623
3624 const MediaList &llChildren = pMedium->getChildren();
3625 for (MediaList::const_iterator it = llChildren.begin();
3626 it != llChildren.end();
3627 ++it)
3628 {
3629 Medium *pChild = *it;
3630 pushMediumToListWithChildren(llMedia, pChild);
3631 }
3632
3633 Log(("Pushing medium %RTuuid\n", pMedium->getId().raw()));
3634 llMedia.push_back(pMedium);
3635}
3636
3637/**
3638 * Unregisters all Medium objects which belong to the given machine registry.
3639 * Gets called from Machine::uninit() just before the machine object dies
3640 * and must only be called with a machine UUID as the registry ID.
3641 *
3642 * Locks the media tree.
3643 *
3644 * @param uuidMachine Medium registry ID (always a machine UUID)
3645 * @return
3646 */
3647HRESULT VirtualBox::unregisterMachineMedia(const Guid &uuidMachine)
3648{
3649 Assert(!uuidMachine.isEmpty());
3650
3651 LogFlowFuncEnter();
3652
3653 AutoCaller autoCaller(this);
3654 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
3655
3656 MediaList llMedia2Close;
3657
3658 {
3659 AutoWriteLock mlock(getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3660 for (MediaOList::iterator it = m->allHardDisks.getList().begin();
3661 it != m->allHardDisks.getList().end();
3662 ++it)
3663 {
3664 ComObjPtr<Medium> pMedium = *it;
3665
3666 if (pMedium->isInRegistry(uuidMachine))
3667 // recursively with children first
3668 pushMediumToListWithChildren(llMedia2Close, pMedium);
3669 }
3670 }
3671
3672 for (MediaList::iterator it = llMedia2Close.begin();
3673 it != llMedia2Close.end();
3674 ++it)
3675 {
3676 ComObjPtr<Medium> pMedium = *it;
3677 Log(("Closing medium %RTuuid\n", pMedium->getId().raw()));
3678 AutoCaller mac(pMedium);
3679 pMedium->close(NULL /* pfNeedsGlobalSaveSettings*/, mac);
3680 }
3681
3682 LogFlowFuncLeave();
3683
3684 return S_OK;
3685}
3686
3687/**
3688 * Removes the given machine object from the internal list of registered machines.
3689 * Called from Machine::Unregister().
3690 * @param pMachine
3691 * @param id UUID of the machine. Must be passed by caller because machine may be dead by this time.
3692 * @return
3693 */
3694HRESULT VirtualBox::unregisterMachine(Machine *pMachine,
3695 const Guid &id)
3696{
3697 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3698
3699 // remove from the collection of registered machines
3700 m->allMachines.removeChild(pMachine);
3701
3702 // save the global registry
3703 HRESULT rc = saveSettings();
3704
3705 alock.release();
3706
3707 /* fire an event */
3708 onMachineRegistered(id, FALSE);
3709
3710 return rc;
3711}
3712
3713/**
3714 * Adds uuid to llRegistriesThatNeedSaving unless it's already on the list.
3715 *
3716 * @todo maybe there's something in libstdc++ for this
3717 *
3718 * @param llRegistriesThatNeedSaving
3719 * @param uuid
3720 */
3721void VirtualBox::addGuidToListUniquely(GuidList &llRegistriesThatNeedSaving,
3722 Guid uuid)
3723{
3724 for (GuidList::const_iterator it = llRegistriesThatNeedSaving.begin();
3725 it != llRegistriesThatNeedSaving.end();
3726 ++it)
3727 {
3728 if (*it == uuid)
3729 // uuid is already in list:
3730 return;
3731 }
3732
3733 llRegistriesThatNeedSaving.push_back(uuid);
3734}
3735
3736/**
3737 * Saves all settings files according to the given list of UUIDs, which are
3738 * either machine IDs (in which case Machine::saveSettings is invoked) or
3739 * the global registry UUID (in which case VirtualBox::saveSettings is invoked).
3740 *
3741 * This locks machines and the VirtualBox object as necessary, so better not
3742 * hold any locks before calling this.
3743 *
3744 * @param llRegistriesThatNeedSaving
3745 * @return
3746 */
3747HRESULT VirtualBox::saveRegistries(const GuidList &llRegistriesThatNeedSaving)
3748{
3749 bool fNeedsGlobalSettings = false;
3750 HRESULT rc = S_OK;
3751
3752 for (GuidList::const_iterator it = llRegistriesThatNeedSaving.begin();
3753 it != llRegistriesThatNeedSaving.end();
3754 ++it)
3755 {
3756 const Guid &uuid = *it;
3757
3758 if (uuid == getGlobalRegistryId())
3759 fNeedsGlobalSettings = true;
3760 else
3761 {
3762 // should be machine ID then:
3763 ComObjPtr<Machine> pMachine;
3764 rc = findMachine(uuid,
3765 false /* fPermitInaccessible */,
3766 false /* aSetError */,
3767 &pMachine);
3768 if (SUCCEEDED(rc))
3769 {
3770 AutoCaller autoCaller(pMachine);
3771 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3772 AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
3773 rc = pMachine->saveSettings(&fNeedsGlobalSettings,
3774 Machine::SaveS_Force); // caller said save, so stop arguing
3775 }
3776
3777 if (FAILED(rc))
3778 return rc;
3779 }
3780 }
3781
3782 if (fNeedsGlobalSettings)
3783 {
3784 AutoWriteLock vlock(this COMMA_LOCKVAL_SRC_POS);
3785 rc = saveSettings();
3786 }
3787
3788 return S_OK;
3789}
3790
3791/**
3792 * Creates the path to the specified file according to the path information
3793 * present in the file name.
3794 *
3795 * Note that the given file name must contain the full path otherwise the
3796 * extracted relative path will be created based on the current working
3797 * directory which is normally unknown.
3798 *
3799 * @param aFileName Full file name which path needs to be created.
3800 *
3801 * @return Extended error information on failure to create the path.
3802 */
3803/* static */
3804HRESULT VirtualBox::ensureFilePathExists(const Utf8Str &strFileName)
3805{
3806 Utf8Str strDir(strFileName);
3807 strDir.stripFilename();
3808 if (!RTDirExists(strDir.c_str()))
3809 {
3810 int vrc = RTDirCreateFullPath(strDir.c_str(), 0777);
3811 if (RT_FAILURE(vrc))
3812 return setErrorStatic(E_FAIL,
3813 Utf8StrFmt(tr("Could not create the directory '%s' (%Rrc)"),
3814 strDir.c_str(),
3815 vrc));
3816 }
3817
3818 return S_OK;
3819}
3820
3821/**
3822 * Handles unexpected exceptions by turning them into COM errors in release
3823 * builds or by hitting a breakpoint in the release builds.
3824 *
3825 * Usage pattern:
3826 * @code
3827 try
3828 {
3829 // ...
3830 }
3831 catch (LaLalA)
3832 {
3833 // ...
3834 }
3835 catch (...)
3836 {
3837 rc = VirtualBox::handleUnexpectedExceptions (RT_SRC_POS);
3838 }
3839 * @endcode
3840 *
3841 * @param RT_SRC_POS_DECL "RT_SRC_POS" macro instantiation.
3842 */
3843/* static */
3844HRESULT VirtualBox::handleUnexpectedExceptions(RT_SRC_POS_DECL)
3845{
3846 try
3847 {
3848 /* re-throw the current exception */
3849 throw;
3850 }
3851 catch (const iprt::Error &err) // includes all XML exceptions
3852 {
3853 return setErrorStatic(E_FAIL,
3854 Utf8StrFmt(tr("%s.\n%s[%d] (%s)"),
3855 err.what(),
3856 pszFile, iLine, pszFunction).c_str());
3857 }
3858 catch (const std::exception &err)
3859 {
3860 return setErrorStatic(E_FAIL,
3861 Utf8StrFmt(tr("Unexpected exception: %s [%s]\n%s[%d] (%s)"),
3862 err.what(), typeid(err).name(),
3863 pszFile, iLine, pszFunction).c_str());
3864 }
3865 catch (...)
3866 {
3867 return setErrorStatic(E_FAIL,
3868 Utf8StrFmt(tr("Unknown exception\n%s[%d] (%s)"),
3869 pszFile, iLine, pszFunction).c_str());
3870 }
3871
3872 /* should not get here */
3873 AssertFailed();
3874 return E_FAIL;
3875}
3876
3877const Utf8Str& VirtualBox::settingsFilePath()
3878{
3879 return m->strSettingsFilePath;
3880}
3881
3882/**
3883 * Returns the lock handle which protects the media trees (hard disks,
3884 * DVDs, floppies). As opposed to version 3.1 and earlier, these lists
3885 * are no longer protected by the VirtualBox lock, but by this more
3886 * specialized lock. Mind the locking order: always request this lock
3887 * after the VirtualBox object lock but before the locks of the media
3888 * objects contained in these lists. See AutoLock.h.
3889 */
3890RWLockHandle& VirtualBox::getMediaTreeLockHandle()
3891{
3892 return m->lockMedia;
3893}
3894
3895/**
3896 * Thread function that watches the termination of all client processes
3897 * that have opened sessions using IMachine::LockMachine()
3898 */
3899// static
3900DECLCALLBACK(int) VirtualBox::ClientWatcher(RTTHREAD /* thread */, void *pvUser)
3901{
3902 LogFlowFuncEnter();
3903
3904 VirtualBox *that = (VirtualBox*)pvUser;
3905 Assert(that);
3906
3907 typedef std::vector< ComObjPtr<Machine> > MachineVector;
3908 typedef std::vector< ComObjPtr<SessionMachine> > SessionMachineVector;
3909
3910 SessionMachineVector machines;
3911 MachineVector spawnedMachines;
3912
3913 size_t cnt = 0;
3914 size_t cntSpawned = 0;
3915
3916#if defined(RT_OS_WINDOWS)
3917
3918 HRESULT hrc = CoInitializeEx(NULL,
3919 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
3920 COINIT_SPEED_OVER_MEMORY);
3921 AssertComRC(hrc);
3922
3923 /// @todo (dmik) processes reaping!
3924
3925 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
3926 handles[0] = that->m->updateReq;
3927
3928 do
3929 {
3930 AutoCaller autoCaller(that);
3931 /* VirtualBox has been early uninitialized, terminate */
3932 if (!autoCaller.isOk())
3933 break;
3934
3935 do
3936 {
3937 /* release the caller to let uninit() ever proceed */
3938 autoCaller.release();
3939
3940 DWORD rc = ::WaitForMultipleObjects((DWORD)(1 + cnt + cntSpawned),
3941 handles,
3942 FALSE,
3943 INFINITE);
3944
3945 /* Restore the caller before using VirtualBox. If it fails, this
3946 * means VirtualBox is being uninitialized and we must terminate. */
3947 autoCaller.add();
3948 if (!autoCaller.isOk())
3949 break;
3950
3951 bool update = false;
3952
3953 if (rc == WAIT_OBJECT_0)
3954 {
3955 /* update event is signaled */
3956 update = true;
3957 }
3958 else if (rc > WAIT_OBJECT_0 && rc <= (WAIT_OBJECT_0 + cnt))
3959 {
3960 /* machine mutex is released */
3961 (machines[rc - WAIT_OBJECT_0 - 1])->checkForDeath();
3962 update = true;
3963 }
3964 else if (rc > WAIT_ABANDONED_0 && rc <= (WAIT_ABANDONED_0 + cnt))
3965 {
3966 /* machine mutex is abandoned due to client process termination */
3967 (machines[rc - WAIT_ABANDONED_0 - 1])->checkForDeath();
3968 update = true;
3969 }
3970 else if (rc > WAIT_OBJECT_0 + cnt && rc <= (WAIT_OBJECT_0 + cntSpawned))
3971 {
3972 /* spawned VM process has terminated (normally or abnormally) */
3973 (spawnedMachines[rc - WAIT_OBJECT_0 - cnt - 1])->
3974 checkForSpawnFailure();
3975 update = true;
3976 }
3977
3978 if (update)
3979 {
3980 /* close old process handles */
3981 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++i)
3982 CloseHandle(handles[i]);
3983
3984 // lock the machines list for reading
3985 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
3986
3987 /* obtain a new set of opened machines */
3988 cnt = 0;
3989 machines.clear();
3990
3991 for (MachinesOList::iterator it = that->m->allMachines.begin();
3992 it != that->m->allMachines.end();
3993 ++it)
3994 {
3995 /// @todo handle situations with more than 64 objects
3996 AssertMsgBreak((1 + cnt) <= MAXIMUM_WAIT_OBJECTS,
3997 ("MAXIMUM_WAIT_OBJECTS reached"));
3998
3999 ComObjPtr<SessionMachine> sm;
4000 HANDLE ipcSem;
4001 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4002 {
4003 machines.push_back(sm);
4004 handles[1 + cnt] = ipcSem;
4005 ++cnt;
4006 }
4007 }
4008
4009 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4010
4011 /* obtain a new set of spawned machines */
4012 cntSpawned = 0;
4013 spawnedMachines.clear();
4014
4015 for (MachinesOList::iterator it = that->m->allMachines.begin();
4016 it != that->m->allMachines.end();
4017 ++it)
4018 {
4019 /// @todo handle situations with more than 64 objects
4020 AssertMsgBreak((1 + cnt + cntSpawned) <= MAXIMUM_WAIT_OBJECTS,
4021 ("MAXIMUM_WAIT_OBJECTS reached"));
4022
4023 RTPROCESS pid;
4024 if ((*it)->isSessionSpawning(&pid))
4025 {
4026 HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, pid);
4027 AssertMsg(ph != NULL, ("OpenProcess (pid=%d) failed with %d\n",
4028 pid, GetLastError()));
4029 if (rc == 0)
4030 {
4031 spawnedMachines.push_back(*it);
4032 handles[1 + cnt + cntSpawned] = ph;
4033 ++cntSpawned;
4034 }
4035 }
4036 }
4037
4038 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4039
4040 // machines lock unwinds here
4041 }
4042 }
4043 while (true);
4044 }
4045 while (0);
4046
4047 /* close old process handles */
4048 for (size_t i = 1 + cnt; i < 1 + cnt + cntSpawned; ++ i)
4049 CloseHandle(handles[i]);
4050
4051 /* release sets of machines if any */
4052 machines.clear();
4053 spawnedMachines.clear();
4054
4055 ::CoUninitialize();
4056
4057#elif defined(RT_OS_OS2)
4058
4059 /// @todo (dmik) processes reaping!
4060
4061 /* according to PMREF, 64 is the maximum for the muxwait list */
4062 SEMRECORD handles[64];
4063
4064 HMUX muxSem = NULLHANDLE;
4065
4066 do
4067 {
4068 AutoCaller autoCaller(that);
4069 /* VirtualBox has been early uninitialized, terminate */
4070 if (!autoCaller.isOk())
4071 break;
4072
4073 do
4074 {
4075 /* release the caller to let uninit() ever proceed */
4076 autoCaller.release();
4077
4078 int vrc = RTSemEventWait(that->m->updateReq, 500);
4079
4080 /* Restore the caller before using VirtualBox. If it fails, this
4081 * means VirtualBox is being uninitialized and we must terminate. */
4082 autoCaller.add();
4083 if (!autoCaller.isOk())
4084 break;
4085
4086 bool update = false;
4087 bool updateSpawned = false;
4088
4089 if (RT_SUCCESS(vrc))
4090 {
4091 /* update event is signaled */
4092 update = true;
4093 updateSpawned = true;
4094 }
4095 else
4096 {
4097 AssertMsg(vrc == VERR_TIMEOUT || vrc == VERR_INTERRUPTED,
4098 ("RTSemEventWait returned %Rrc\n", vrc));
4099
4100 /* are there any mutexes? */
4101 if (cnt > 0)
4102 {
4103 /* figure out what's going on with machines */
4104
4105 unsigned long semId = 0;
4106 APIRET arc = ::DosWaitMuxWaitSem(muxSem,
4107 SEM_IMMEDIATE_RETURN, &semId);
4108
4109 if (arc == NO_ERROR)
4110 {
4111 /* machine mutex is normally released */
4112 Assert(semId >= 0 && semId < cnt);
4113 if (semId >= 0 && semId < cnt)
4114 {
4115#if 0//def DEBUG
4116 {
4117 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4118 LogFlowFunc(("released mutex: machine='%ls'\n",
4119 machines[semId]->name().raw()));
4120 }
4121#endif
4122 machines[semId]->checkForDeath();
4123 }
4124 update = true;
4125 }
4126 else if (arc == ERROR_SEM_OWNER_DIED)
4127 {
4128 /* machine mutex is abandoned due to client process
4129 * termination; find which mutex is in the Owner Died
4130 * state */
4131 for (size_t i = 0; i < cnt; ++ i)
4132 {
4133 PID pid; TID tid;
4134 unsigned long reqCnt;
4135 arc = DosQueryMutexSem((HMTX)handles[i].hsemCur, &pid, &tid, &reqCnt);
4136 if (arc == ERROR_SEM_OWNER_DIED)
4137 {
4138 /* close the dead mutex as asked by PMREF */
4139 ::DosCloseMutexSem((HMTX)handles[i].hsemCur);
4140
4141 Assert(i >= 0 && i < cnt);
4142 if (i >= 0 && i < cnt)
4143 {
4144#if 0//def DEBUG
4145 {
4146 AutoReadLock machineLock(machines[semId] COMMA_LOCKVAL_SRC_POS);
4147 LogFlowFunc(("mutex owner dead: machine='%ls'\n",
4148 machines[i]->name().raw()));
4149 }
4150#endif
4151 machines[i]->checkForDeath();
4152 }
4153 }
4154 }
4155 update = true;
4156 }
4157 else
4158 AssertMsg(arc == ERROR_INTERRUPT || arc == ERROR_TIMEOUT,
4159 ("DosWaitMuxWaitSem returned %d\n", arc));
4160 }
4161
4162 /* are there any spawning sessions? */
4163 if (cntSpawned > 0)
4164 {
4165 for (size_t i = 0; i < cntSpawned; ++ i)
4166 updateSpawned |= (spawnedMachines[i])->
4167 checkForSpawnFailure();
4168 }
4169 }
4170
4171 if (update || updateSpawned)
4172 {
4173 AutoReadLock thatLock(that COMMA_LOCKVAL_SRC_POS);
4174
4175 if (update)
4176 {
4177 /* close the old muxsem */
4178 if (muxSem != NULLHANDLE)
4179 ::DosCloseMuxWaitSem(muxSem);
4180
4181 /* obtain a new set of opened machines */
4182 cnt = 0;
4183 machines.clear();
4184
4185 for (MachinesOList::iterator it = that->m->allMachines.begin();
4186 it != that->m->allMachines.end(); ++ it)
4187 {
4188 /// @todo handle situations with more than 64 objects
4189 AssertMsg(cnt <= 64 /* according to PMREF */,
4190 ("maximum of 64 mutex semaphores reached (%d)",
4191 cnt));
4192
4193 ComObjPtr<SessionMachine> sm;
4194 HMTX ipcSem;
4195 if ((*it)->isSessionOpenOrClosing(sm, NULL, &ipcSem))
4196 {
4197 machines.push_back(sm);
4198 handles[cnt].hsemCur = (HSEM)ipcSem;
4199 handles[cnt].ulUser = cnt;
4200 ++ cnt;
4201 }
4202 }
4203
4204 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4205
4206 if (cnt > 0)
4207 {
4208 /* create a new muxsem */
4209 APIRET arc = ::DosCreateMuxWaitSem(NULL, &muxSem, cnt,
4210 handles,
4211 DCMW_WAIT_ANY);
4212 AssertMsg(arc == NO_ERROR,
4213 ("DosCreateMuxWaitSem returned %d\n", arc));
4214 NOREF(arc);
4215 }
4216 }
4217
4218 if (updateSpawned)
4219 {
4220 /* obtain a new set of spawned machines */
4221 spawnedMachines.clear();
4222
4223 for (MachinesOList::iterator it = that->m->allMachines.begin();
4224 it != that->m->allMachines.end(); ++ it)
4225 {
4226 if ((*it)->isSessionSpawning())
4227 spawnedMachines.push_back(*it);
4228 }
4229
4230 cntSpawned = spawnedMachines.size();
4231 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4232 }
4233 }
4234 }
4235 while (true);
4236 }
4237 while (0);
4238
4239 /* close the muxsem */
4240 if (muxSem != NULLHANDLE)
4241 ::DosCloseMuxWaitSem(muxSem);
4242
4243 /* release sets of machines if any */
4244 machines.clear();
4245 spawnedMachines.clear();
4246
4247#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
4248
4249 bool update = false;
4250 bool updateSpawned = false;
4251
4252 do
4253 {
4254 AutoCaller autoCaller(that);
4255 if (!autoCaller.isOk())
4256 break;
4257
4258 do
4259 {
4260 /* release the caller to let uninit() ever proceed */
4261 autoCaller.release();
4262
4263 int rc = RTSemEventWait(that->m->updateReq, 500);
4264
4265 /*
4266 * Restore the caller before using VirtualBox. If it fails, this
4267 * means VirtualBox is being uninitialized and we must terminate.
4268 */
4269 autoCaller.add();
4270 if (!autoCaller.isOk())
4271 break;
4272
4273 if (RT_SUCCESS(rc) || update || updateSpawned)
4274 {
4275 /* RT_SUCCESS(rc) means an update event is signaled */
4276
4277 // lock the machines list for reading
4278 AutoReadLock thatLock(that->m->allMachines.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4279
4280 if (RT_SUCCESS(rc) || update)
4281 {
4282 /* obtain a new set of opened machines */
4283 machines.clear();
4284
4285 for (MachinesOList::iterator it = that->m->allMachines.begin();
4286 it != that->m->allMachines.end();
4287 ++it)
4288 {
4289 ComObjPtr<SessionMachine> sm;
4290 if ((*it)->isSessionOpenOrClosing(sm))
4291 machines.push_back(sm);
4292 }
4293
4294 cnt = machines.size();
4295 LogFlowFunc(("UPDATE: direct session count = %d\n", cnt));
4296 }
4297
4298 if (RT_SUCCESS(rc) || updateSpawned)
4299 {
4300 /* obtain a new set of spawned machines */
4301 spawnedMachines.clear();
4302
4303 for (MachinesOList::iterator it = that->m->allMachines.begin();
4304 it != that->m->allMachines.end();
4305 ++it)
4306 {
4307 if ((*it)->isSessionSpawning())
4308 spawnedMachines.push_back(*it);
4309 }
4310
4311 cntSpawned = spawnedMachines.size();
4312 LogFlowFunc(("UPDATE: spawned session count = %d\n", cntSpawned));
4313 }
4314
4315 // machines lock unwinds here
4316 }
4317
4318 update = false;
4319 for (size_t i = 0; i < cnt; ++ i)
4320 update |= (machines[i])->checkForDeath();
4321
4322 updateSpawned = false;
4323 for (size_t i = 0; i < cntSpawned; ++ i)
4324 updateSpawned |= (spawnedMachines[i])->checkForSpawnFailure();
4325
4326 /* reap child processes */
4327 {
4328 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
4329 if (that->m->llProcesses.size())
4330 {
4331 LogFlowFunc(("UPDATE: child process count = %d\n",
4332 that->m->llProcesses.size()));
4333 VirtualBox::Data::ProcessList::iterator it = that->m->llProcesses.begin();
4334 while (it != that->m->llProcesses.end())
4335 {
4336 RTPROCESS pid = *it;
4337 RTPROCSTATUS status;
4338 int vrc = ::RTProcWait(pid, RTPROCWAIT_FLAGS_NOBLOCK, &status);
4339 if (vrc == VINF_SUCCESS)
4340 {
4341 LogFlowFunc(("pid %d (%x) was reaped, status=%d, reason=%d\n",
4342 pid, pid, status.iStatus,
4343 status.enmReason));
4344 it = that->m->llProcesses.erase(it);
4345 }
4346 else
4347 {
4348 LogFlowFunc(("pid %d (%x) was NOT reaped, vrc=%Rrc\n",
4349 pid, pid, vrc));
4350 if (vrc != VERR_PROCESS_RUNNING)
4351 {
4352 /* remove the process if it is not already running */
4353 it = that->m->llProcesses.erase(it);
4354 }
4355 else
4356 ++ it;
4357 }
4358 }
4359 }
4360 }
4361 }
4362 while (true);
4363 }
4364 while (0);
4365
4366 /* release sets of machines if any */
4367 machines.clear();
4368 spawnedMachines.clear();
4369
4370#else
4371# error "Port me!"
4372#endif
4373
4374 LogFlowFuncLeave();
4375 return 0;
4376}
4377
4378/**
4379 * Thread function that handles custom events posted using #postEvent().
4380 */
4381// static
4382DECLCALLBACK(int) VirtualBox::AsyncEventHandler(RTTHREAD thread, void *pvUser)
4383{
4384 LogFlowFuncEnter();
4385
4386 AssertReturn(pvUser, VERR_INVALID_POINTER);
4387
4388 // create an event queue for the current thread
4389 EventQueue *eventQ = new EventQueue();
4390 AssertReturn(eventQ, VERR_NO_MEMORY);
4391
4392 // return the queue to the one who created this thread
4393 *(static_cast <EventQueue **>(pvUser)) = eventQ;
4394 // signal that we're ready
4395 RTThreadUserSignal(thread);
4396
4397 while (RT_SUCCESS(eventQ->processEventQueue(RT_INDEFINITE_WAIT)))
4398 /* nothing */ ;
4399
4400 delete eventQ;
4401
4402 LogFlowFuncLeave();
4403
4404 return 0;
4405}
4406
4407
4408////////////////////////////////////////////////////////////////////////////////
4409
4410/**
4411 * Takes the current list of registered callbacks of the managed VirtualBox
4412 * instance, and calls #handleCallback() for every callback item from the
4413 * list, passing the item as an argument.
4414 *
4415 * @note Locks the managed VirtualBox object for reading but leaves the lock
4416 * before iterating over callbacks and calling their methods.
4417 */
4418void *VirtualBox::CallbackEvent::handler()
4419{
4420 if (!mVirtualBox)
4421 return NULL;
4422
4423 AutoCaller autoCaller(mVirtualBox);
4424 if (!autoCaller.isOk())
4425 {
4426 LogWarningFunc(("VirtualBox has been uninitialized (state=%d), the callback event is discarded!\n",
4427 autoCaller.state()));
4428 /* We don't need mVirtualBox any more, so release it */
4429 mVirtualBox = NULL;
4430 return NULL;
4431 }
4432
4433 {
4434 VBoxEventDesc evDesc;
4435 prepareEventDesc(mVirtualBox->m->pEventSource, evDesc);
4436
4437 evDesc.fire(/* don't wait for delivery */0);
4438 }
4439
4440 mVirtualBox = NULL; /* Not needed any longer. Still make sense to do this? */
4441 return NULL;
4442}
4443
4444//STDMETHODIMP VirtualBox::CreateDHCPServerForInterface(/*IHostNetworkInterface * aIinterface,*/ IDHCPServer ** aServer)
4445//{
4446// return E_NOTIMPL;
4447//}
4448
4449STDMETHODIMP VirtualBox::CreateDHCPServer(IN_BSTR aName, IDHCPServer ** aServer)
4450{
4451 CheckComArgStrNotEmptyOrNull(aName);
4452 CheckComArgNotNull(aServer);
4453
4454 AutoCaller autoCaller(this);
4455 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4456
4457 ComObjPtr<DHCPServer> dhcpServer;
4458 dhcpServer.createObject();
4459 HRESULT rc = dhcpServer->init(this, aName);
4460 if (FAILED(rc)) return rc;
4461
4462 rc = registerDHCPServer(dhcpServer, true);
4463 if (FAILED(rc)) return rc;
4464
4465 dhcpServer.queryInterfaceTo(aServer);
4466
4467 return rc;
4468}
4469
4470STDMETHODIMP VirtualBox::FindDHCPServerByNetworkName(IN_BSTR aName, IDHCPServer ** aServer)
4471{
4472 CheckComArgStrNotEmptyOrNull(aName);
4473 CheckComArgNotNull(aServer);
4474
4475 AutoCaller autoCaller(this);
4476 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4477
4478 HRESULT rc;
4479 Bstr bstr;
4480 ComPtr<DHCPServer> found;
4481
4482 AutoReadLock alock(m->allDHCPServers.getLockHandle() COMMA_LOCKVAL_SRC_POS);
4483
4484 for (DHCPServersOList::const_iterator it = m->allDHCPServers.begin();
4485 it != m->allDHCPServers.end();
4486 ++it)
4487 {
4488 rc = (*it)->COMGETTER(NetworkName)(bstr.asOutParam());
4489 if (FAILED(rc)) throw rc;
4490
4491 if (bstr == aName)
4492 {
4493 found = *it;
4494 break;
4495 }
4496 }
4497
4498 if (!found)
4499 return E_INVALIDARG;
4500
4501 return found.queryInterfaceTo(aServer);
4502}
4503
4504STDMETHODIMP VirtualBox::RemoveDHCPServer(IDHCPServer * aServer)
4505{
4506 CheckComArgNotNull(aServer);
4507
4508 AutoCaller autoCaller(this);
4509 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4510
4511 HRESULT rc = unregisterDHCPServer(static_cast<DHCPServer *>(aServer), true);
4512
4513 return rc;
4514}
4515
4516/**
4517 * Remembers the given dhcp server by storing it in the hard disk registry.
4518 *
4519 * @param aDHCPServer Dhcp Server object to remember.
4520 * @param aSaveRegistry @c true to save hard disk registry to disk (default).
4521 *
4522 * When @a aSaveRegistry is @c true, this operation may fail because of the
4523 * failed #saveSettings() method it calls. In this case, the dhcp server object
4524 * will not be remembered. It is therefore the responsibility of the caller to
4525 * call this method as the last step of some action that requires registration
4526 * in order to make sure that only fully functional dhcp server objects get
4527 * registered.
4528 *
4529 * @note Locks this object for writing and @a aDHCPServer for reading.
4530 */
4531HRESULT VirtualBox::registerDHCPServer(DHCPServer *aDHCPServer,
4532 bool aSaveRegistry /*= true*/)
4533{
4534 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4535
4536 AutoCaller autoCaller(this);
4537 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4538
4539 AutoCaller dhcpServerCaller(aDHCPServer);
4540 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4541
4542 Bstr name;
4543 HRESULT rc;
4544 rc = aDHCPServer->COMGETTER(NetworkName)(name.asOutParam());
4545 if (FAILED(rc)) return rc;
4546
4547 ComPtr<IDHCPServer> existing;
4548 rc = FindDHCPServerByNetworkName(name.raw(), existing.asOutParam());
4549 if (SUCCEEDED(rc))
4550 return E_INVALIDARG;
4551
4552 rc = S_OK;
4553
4554 m->allDHCPServers.addChild(aDHCPServer);
4555
4556 if (aSaveRegistry)
4557 {
4558 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4559 rc = saveSettings();
4560 vboxLock.release();
4561
4562 if (FAILED(rc))
4563 unregisterDHCPServer(aDHCPServer, false /* aSaveRegistry */);
4564 }
4565
4566 return rc;
4567}
4568
4569/**
4570 * Removes the given hard disk from the hard disk registry.
4571 *
4572 * @param aHardDisk Hard disk object to remove.
4573 * @param aSaveRegistry @c true to save hard disk registry to disk (default).
4574 *
4575 * When @a aSaveRegistry is @c true, this operation may fail because of the
4576 * failed #saveSettings() method it calls. In this case, the hard disk object
4577 * will NOT be removed from the registry when this method returns. It is
4578 * therefore the responsibility of the caller to call this method as the first
4579 * step of some action that requires unregistration, before calling uninit() on
4580 * @a aHardDisk.
4581 *
4582 * @note Locks this object for writing and @a aHardDisk for reading.
4583 */
4584HRESULT VirtualBox::unregisterDHCPServer(DHCPServer *aDHCPServer,
4585 bool aSaveRegistry /*= true*/)
4586{
4587 AssertReturn(aDHCPServer != NULL, E_INVALIDARG);
4588
4589 AutoCaller autoCaller(this);
4590 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
4591
4592 AutoCaller dhcpServerCaller(aDHCPServer);
4593 AssertComRCReturn(dhcpServerCaller.rc(), dhcpServerCaller.rc());
4594
4595 m->allDHCPServers.removeChild(aDHCPServer);
4596
4597 HRESULT rc = S_OK;
4598
4599 if (aSaveRegistry)
4600 {
4601 AutoWriteLock vboxLock(this COMMA_LOCKVAL_SRC_POS);
4602 rc = saveSettings();
4603 vboxLock.release();
4604
4605 if (FAILED(rc))
4606 registerDHCPServer(aDHCPServer, false /* aSaveRegistry */);
4607 }
4608
4609 return rc;
4610}
4611
4612/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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