VirtualBox

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

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

Main: move handleUnexpectedExceptions method to VirtualBoxBase

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

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