VirtualBox

source: vbox/trunk/src/VBox/Main/glue/initterm.cpp@ 25414

Last change on this file since 25414 was 23175, checked in by vboxsync, 15 years ago

glue/initterm.cpp: Don't assume RTThreadSelf() won't return NIL_RTTHREAD in com::Initialize(). Should fix assertion on Windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.7 KB
Line 
1/* $Id: initterm.cpp 23175 2009-09-21 09:54:42Z vboxsync $ */
2
3/** @file
4 * MS COM / XPCOM Abstraction Layer - Initialization and Termination.
5 */
6
7/*
8 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#if !defined (VBOX_WITH_XPCOM)
24
25#include <objbase.h>
26
27#else /* !defined (VBOX_WITH_XPCOM) */
28
29#include <stdlib.h>
30
31/* XPCOM_GLUE is defined when the client uses the standalone glue
32 * (i.e. dynamically picks up the existing XPCOM shared library installation).
33 * This is not the case for VirtualBox XPCOM clients (they are always
34 * distrubuted with the self-built XPCOM library, and therefore have a binary
35 * dependency on it) but left here for clarity.
36 */
37#if defined (XPCOM_GLUE)
38#include <nsXPCOMGlue.h>
39#endif
40
41#include <nsIComponentRegistrar.h>
42#include <nsIServiceManager.h>
43#include <nsCOMPtr.h>
44#include <nsEventQueueUtils.h>
45#include <nsEmbedString.h>
46
47#include <nsILocalFile.h>
48#include <nsIDirectoryService.h>
49#include <nsDirectoryServiceDefs.h>
50
51#endif /* !defined (VBOX_WITH_XPCOM) */
52
53#include "VBox/com/com.h"
54#include "VBox/com/assert.h"
55#include "VBox/com/EventQueue.h"
56
57#include "../include/Logging.h"
58
59#include <iprt/asm.h>
60#include <iprt/env.h>
61#include <iprt/param.h>
62#include <iprt/path.h>
63#include <iprt/string.h>
64#include <iprt/thread.h>
65
66#include <VBox/err.h>
67
68namespace com
69{
70
71#if defined (VBOX_WITH_XPCOM)
72
73class DirectoryServiceProvider : public nsIDirectoryServiceProvider
74{
75public:
76
77 NS_DECL_ISUPPORTS
78
79 DirectoryServiceProvider()
80 : mCompRegLocation (NULL), mXPTIDatLocation (NULL)
81 , mComponentDirLocation (NULL), mCurrProcDirLocation (NULL)
82 {}
83
84 virtual ~DirectoryServiceProvider();
85
86 HRESULT init (const char *aCompRegLocation,
87 const char *aXPTIDatLocation,
88 const char *aComponentDirLocation,
89 const char *aCurrProcDirLocation);
90
91 NS_DECL_NSIDIRECTORYSERVICEPROVIDER
92
93private:
94
95 char *mCompRegLocation;
96 char *mXPTIDatLocation;
97 char *mComponentDirLocation;
98 char *mCurrProcDirLocation;
99};
100
101NS_IMPL_ISUPPORTS1 (DirectoryServiceProvider, nsIDirectoryServiceProvider)
102
103DirectoryServiceProvider::~DirectoryServiceProvider()
104{
105 if (mCompRegLocation)
106 {
107 RTStrFree (mCompRegLocation);
108 mCompRegLocation = NULL;
109 }
110 if (mXPTIDatLocation)
111 {
112 RTStrFree (mXPTIDatLocation);
113 mXPTIDatLocation = NULL;
114 }
115 if (mComponentDirLocation)
116 {
117 RTStrFree (mComponentDirLocation);
118 mComponentDirLocation = NULL;
119 }
120 if (mCurrProcDirLocation)
121 {
122 RTStrFree (mCurrProcDirLocation);
123 mCurrProcDirLocation = NULL;
124 }
125}
126
127/**
128 * @param aCompRegLocation Path to compreg.dat, in Utf8.
129 * @param aXPTIDatLocation Path to xpti.data, in Utf8.
130 */
131HRESULT
132DirectoryServiceProvider::init (const char *aCompRegLocation,
133 const char *aXPTIDatLocation,
134 const char *aComponentDirLocation,
135 const char *aCurrProcDirLocation)
136{
137 AssertReturn(aCompRegLocation, NS_ERROR_INVALID_ARG);
138 AssertReturn(aXPTIDatLocation, NS_ERROR_INVALID_ARG);
139
140 int vrc = RTStrUtf8ToCurrentCP (&mCompRegLocation, aCompRegLocation);
141 if (RT_SUCCESS(vrc))
142 vrc = RTStrUtf8ToCurrentCP (&mXPTIDatLocation, aXPTIDatLocation);
143 if (RT_SUCCESS(vrc) && aComponentDirLocation)
144 vrc = RTStrUtf8ToCurrentCP (&mComponentDirLocation, aComponentDirLocation);
145 if (RT_SUCCESS(vrc) && aCurrProcDirLocation)
146 vrc = RTStrUtf8ToCurrentCP (&mCurrProcDirLocation, aCurrProcDirLocation);
147
148 return RT_SUCCESS(vrc) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
149}
150
151NS_IMETHODIMP
152DirectoryServiceProvider::GetFile (const char *aProp,
153 PRBool *aPersistent,
154 nsIFile **aRetval)
155{
156 nsCOMPtr <nsILocalFile> localFile;
157 nsresult rv = NS_ERROR_FAILURE;
158
159 *aRetval = nsnull;
160 *aPersistent = PR_TRUE;
161
162 const char *fileLocation = NULL;
163
164 if (strcmp (aProp, NS_XPCOM_COMPONENT_REGISTRY_FILE) == 0)
165 fileLocation = mCompRegLocation;
166 else if (strcmp (aProp, NS_XPCOM_XPTI_REGISTRY_FILE) == 0)
167 fileLocation = mXPTIDatLocation;
168 else if (mComponentDirLocation && strcmp (aProp, NS_XPCOM_COMPONENT_DIR) == 0)
169 fileLocation = mComponentDirLocation;
170 else if (mCurrProcDirLocation && strcmp (aProp, NS_XPCOM_CURRENT_PROCESS_DIR) == 0)
171 fileLocation = mCurrProcDirLocation;
172 else
173 return NS_ERROR_FAILURE;
174
175 rv = NS_NewNativeLocalFile (nsEmbedCString (fileLocation),
176 PR_TRUE, getter_AddRefs (localFile));
177 if (NS_FAILED(rv))
178 return rv;
179
180 return localFile->QueryInterface (NS_GET_IID (nsIFile),
181 (void **) aRetval);
182}
183
184/**
185 * Global XPCOM initialization flag (we maintain it ourselves since XPCOM
186 * doesn't provide such functionality)
187 */
188static bool volatile gIsXPCOMInitialized = false;
189
190/**
191 * Number of Initialize() calls on the main thread.
192 */
193static unsigned int gXPCOMInitCount = 0;
194
195#else /* !defined (VBOX_WITH_XPCOM) */
196
197/**
198 * The COM main thread handle. (The first caller of com::Initialize().)
199 */
200static RTTHREAD volatile gCOMMainThread = NIL_RTTHREAD;
201
202/**
203 * Number of Initialize() calls on the main thread.
204 */
205static uint32_t gCOMMainInitCount = 0;
206
207#endif /* !defined (VBOX_WITH_XPCOM) */
208
209
210/**
211 * Initializes the COM runtime.
212 *
213 * This method must be called on each thread of the client application that
214 * wants to access COM facilities. The initialization must be performed before
215 * calling any other COM method or attempting to instantiate COM objects.
216 *
217 * On platforms using XPCOM, this method uses the following scheme to search for
218 * XPCOM runtime:
219 *
220 * 1. If the VBOX_APP_HOME environment variable is set, the path it specifies
221 * is used to search XPCOM libraries and components. If this method fails to
222 * initialize XPCOM runtime using this path, it will immediately return a
223 * failure and will NOT check for other paths as described below.
224 *
225 * 2. If VBOX_APP_HOME is not set, this methods tries the following paths in the
226 * given order:
227 *
228 * a) Compiled-in application data directory (as returned by
229 * RTPathAppPrivateArch())
230 * b) "/usr/lib/virtualbox" (Linux only)
231 * c) "/opt/VirtualBox" (Linux only)
232 *
233 * The first path for which the initialization succeeds will be used.
234 *
235 * On MS COM platforms, the COM runtime is provided by the system and does not
236 * need to be searched for.
237 *
238 * Once the COM subsystem is no longer necessary on a given thread, Shutdown()
239 * must be called to free resources allocated for it. Note that a thread may
240 * call Initialize() several times but for each of tese calls there must be a
241 * corresponding Shutdown() call.
242 *
243 * @return S_OK on success and a COM result code in case of failure.
244 */
245HRESULT Initialize()
246{
247 HRESULT rc = E_FAIL;
248
249#if !defined (VBOX_WITH_XPCOM)
250
251 DWORD flags = COINIT_MULTITHREADED |
252 COINIT_DISABLE_OLE1DDE |
253 COINIT_SPEED_OVER_MEMORY;
254
255 rc = CoInitializeEx (NULL, flags);
256
257 /// @todo the below rough method of changing the aparment type doesn't
258 /// work on some systems for unknown reason (CoUninitialize() simply does
259 /// nothing there, or at least all 10 000 of subsequent CoInitializeEx()
260 /// continue to return RPC_E_CHANGED_MODE there). The problem on those
261 /// systems is related to the "Extend support for advanced text services
262 /// to all programs" checkbox in the advanced language settings dialog,
263 /// i.e. the problem appears when this checkbox is checked and disappears
264 /// if you clear it. For this reason, we disable the code below and
265 /// instead initialize COM in MTA as early as possible, before 3rd party
266 /// libraries we use have done so (i.e. Qt).
267# if 0
268 /* If we fail to set the necessary apartment model, it may mean that some
269 * DLL that was indirectly loaded by the process calling this function has
270 * already initialized COM on the given thread in an incompatible way
271 * which we can't leave with. Therefore, we try to fix this by using the
272 * brute force method: */
273
274 if (rc == RPC_E_CHANGED_MODE)
275 {
276 /* Before we use brute force, we need to check if we are in the
277 * neutral threaded apartment -- in this case there is no need to
278 * worry at all. */
279
280 rc = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);
281 if (rc == RPC_E_CHANGED_MODE)
282 {
283 /* This is a neutral apartment, reset the error */
284 rc = S_OK;
285
286 LogFlowFunc (("COM is already initialized in neutral threaded "
287 "apartment mode,\nwill accept it.\n"));
288 }
289 else if (rc == S_FALSE)
290 {
291 /* balance the test CoInitializeEx above */
292 CoUninitialize();
293 rc = RPC_E_CHANGED_MODE;
294
295 LogFlowFunc (("COM is already initialized in single threaded "
296 "apartment mode,\nwill reinitialize as "
297 "multi threaded.\n"));
298
299 enum { MaxTries = 10000 };
300 int tries = MaxTries;
301 while (rc == RPC_E_CHANGED_MODE && tries --)
302 {
303 CoUninitialize();
304 rc = CoInitializeEx (NULL, flags);
305 if (rc == S_OK)
306 {
307 /* We've successfully reinitialized COM; restore the
308 * initialization reference counter */
309
310 LogFlowFunc (("Will call CoInitializeEx() %d times.\n",
311 MaxTries - tries));
312
313 while (tries ++ < MaxTries)
314 {
315 rc = CoInitializeEx (NULL, flags);
316 Assert (rc == S_FALSE);
317 }
318 }
319 }
320 }
321 else
322 AssertMsgFailed (("rc=%08X\n", rc));
323 }
324# endif
325
326 /* the overall result must be either S_OK or S_FALSE (S_FALSE means
327 * "already initialized using the same apartment model") */
328 AssertMsg (rc == S_OK || rc == S_FALSE, ("rc=%08X\n", rc));
329
330 /* To be flow compatible with the XPCOM case, we return here if this isn't
331 * the main thread or if it isn't its first initialization call.
332 * Note! CoInitializeEx and CoUninitialize does it's own reference
333 * counting, so this exercise is entirely for the EventQueue init. */
334 bool fRc;
335 RTTHREAD hSelf = RTThreadSelf ();
336 if (hSelf != NIL_RTTHREAD)
337 ASMAtomicCmpXchgHandle (&gCOMMainThread, hSelf, NIL_RTTHREAD, fRc);
338 else
339 fRc = false;
340 if (!fRc)
341 {
342 if ( gCOMMainThread == hSelf
343 && SUCCEEDED (rc))
344 gCOMMainInitCount++;
345
346 AssertComRC (rc);
347 return rc;
348 }
349 Assert (RTThreadIsMain (hSelf));
350
351 /* this is the first main thread initialization */
352 Assert (gCOMMainInitCount == 0);
353 if (SUCCEEDED (rc))
354 gCOMMainInitCount = 1;
355
356#else /* !defined (VBOX_WITH_XPCOM) */
357
358 if (ASMAtomicXchgBool (&gIsXPCOMInitialized, true) == true)
359 {
360 /* XPCOM is already initialized on the main thread, no special
361 * initialization is necessary on additional threads. Just increase
362 * the init counter if it's a main thread again (to correctly support
363 * nested calls to Initialize()/Shutdown() for compatibility with
364 * Win32). */
365
366 nsCOMPtr <nsIEventQueue> eventQ;
367 rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
368
369 if (NS_SUCCEEDED(rc))
370 {
371 PRBool isOnMainThread = PR_FALSE;
372 rc = eventQ->IsOnCurrentThread (&isOnMainThread);
373 if (NS_SUCCEEDED(rc) && isOnMainThread)
374 ++ gXPCOMInitCount;
375 }
376
377 AssertComRC (rc);
378 return rc;
379 }
380 Assert (RTThreadIsMain (RTThreadSelf()));
381
382 /* this is the first initialization */
383 gXPCOMInitCount = 1;
384 bool const fInitEventQueues = true;
385
386 /* prepare paths for registry files */
387 char userHomeDir [RTPATH_MAX];
388 int vrc = GetVBoxUserHomeDirectory (userHomeDir, sizeof (userHomeDir));
389 AssertRCReturn (vrc, NS_ERROR_FAILURE);
390
391 char compReg [RTPATH_MAX];
392 char xptiDat [RTPATH_MAX];
393
394 /** @todo use RTPathAppend */
395 RTStrPrintf (compReg, sizeof (compReg), "%s%c%s",
396 userHomeDir, RTPATH_DELIMITER, "compreg.dat");
397 RTStrPrintf (xptiDat, sizeof (xptiDat), "%s%c%s",
398 userHomeDir, RTPATH_DELIMITER, "xpti.dat");
399
400 LogFlowFunc (("component registry : \"%s\"\n", compReg));
401 LogFlowFunc (("XPTI data file : \"%s\"\n", xptiDat));
402
403#if defined (XPCOM_GLUE)
404 XPCOMGlueStartup (nsnull);
405#endif
406
407 static const char *kAppPathsToProbe[] =
408 {
409 NULL, /* 0: will use VBOX_APP_HOME */
410 NULL, /* 1: will try RTPathAppPrivateArch() */
411#ifdef RT_OS_LINUX
412 "/usr/lib/virtualbox",
413 "/opt/VirtualBox",
414#elif RT_OS_SOLARIS
415 "/opt/VirtualBox/amd64",
416 "/opt/VirtualBox/i386",
417#elif RT_OS_DARWIN
418 "/Application/VirtualBox.app/Contents/MacOS",
419#endif
420 };
421
422 /* Find out the directory where VirtualBox binaries are located */
423 for (size_t i = 0; i < RT_ELEMENTS (kAppPathsToProbe); ++ i)
424 {
425 char appHomeDir [RTPATH_MAX];
426 appHomeDir [RTPATH_MAX - 1] = '\0';
427
428 if (i == 0)
429 {
430 /* Use VBOX_APP_HOME if present */
431 if (!RTEnvExist ("VBOX_APP_HOME"))
432 continue;
433
434 strncpy (appHomeDir, RTEnvGet ("VBOX_APP_HOME"), RTPATH_MAX - 1); /** @todo r=bird: Use RTEnvGetEx. */
435 }
436 else if (i == 1)
437 {
438 /* Use RTPathAppPrivateArch() first */
439 vrc = RTPathAppPrivateArch (appHomeDir, sizeof (appHomeDir));
440 AssertRC (vrc);
441 if (RT_FAILURE(vrc))
442 {
443 rc = NS_ERROR_FAILURE;
444 continue;
445 }
446 }
447 else
448 {
449 /* Iterate over all other paths */
450 strncpy (appHomeDir, kAppPathsToProbe [i], RTPATH_MAX - 1);
451 }
452
453 nsCOMPtr <DirectoryServiceProvider> dsProv;
454
455 char compDir [RTPATH_MAX];
456 RTStrPrintf (compDir, sizeof (compDir), "%s%c%s",
457 appHomeDir, RTPATH_DELIMITER, "components");
458 LogFlowFunc (("component directory : \"%s\"\n", compDir));
459
460 dsProv = new DirectoryServiceProvider();
461 if (dsProv)
462 rc = dsProv->init (compReg, xptiDat, compDir, appHomeDir);
463 else
464 rc = NS_ERROR_OUT_OF_MEMORY;
465 if (NS_FAILED (rc))
466 break;
467
468 /* Setup the application path for NS_InitXPCOM2. Note that we properly
469 * answer the NS_XPCOM_CURRENT_PROCESS_DIR query in our directory
470 * service provider but it seems to be activated after the directory
471 * service is used for the first time (see the source NS_InitXPCOM2). So
472 * use the same value here to be on the safe side. */
473 nsCOMPtr <nsIFile> appDir;
474 {
475 char *appDirCP = NULL;
476 vrc = RTStrUtf8ToCurrentCP (&appDirCP, appHomeDir);
477 if (RT_SUCCESS(vrc))
478 {
479 nsCOMPtr <nsILocalFile> file;
480 rc = NS_NewNativeLocalFile (nsEmbedCString (appDirCP),
481 PR_FALSE, getter_AddRefs (file));
482 if (NS_SUCCEEDED(rc))
483 appDir = do_QueryInterface (file, &rc);
484
485 RTStrFree (appDirCP);
486 }
487 else
488 rc = NS_ERROR_FAILURE;
489 }
490 if (NS_FAILED (rc))
491 break;
492
493 /* Set VBOX_XPCOM_HOME to the same app path to make XPCOM sources that
494 * still use it instead of the directory service happy */
495 {
496 char *pathCP = NULL;
497 vrc = RTStrUtf8ToCurrentCP (&pathCP, appHomeDir);
498 if (RT_SUCCESS(vrc))
499 {
500 vrc = RTEnvSet ("VBOX_XPCOM_HOME", pathCP);
501 RTStrFree (pathCP);
502 }
503 AssertRC (vrc);
504 }
505
506 /* Finally, initialize XPCOM */
507 {
508 nsCOMPtr <nsIServiceManager> serviceManager;
509 rc = NS_InitXPCOM2 (getter_AddRefs (serviceManager),
510 appDir, dsProv);
511
512 if (NS_SUCCEEDED(rc))
513 {
514 nsCOMPtr <nsIComponentRegistrar> registrar =
515 do_QueryInterface (serviceManager, &rc);
516 if (NS_SUCCEEDED(rc))
517 {
518 rc = registrar->AutoRegister (nsnull);
519 if (NS_SUCCEEDED(rc))
520 {
521 /* We succeeded, stop probing paths */
522 LogFlowFunc (("Succeeded.\n"));
523 break;
524 }
525 }
526 }
527 }
528
529 /* clean up before the new try */
530 rc = NS_ShutdownXPCOM (nsnull);
531
532 if (i == 0)
533 {
534 /* We failed with VBOX_APP_HOME, don't probe other paths */
535 break;
536 }
537 }
538
539#endif /* !defined (VBOX_WITH_XPCOM) */
540
541 AssertComRC (rc);
542
543 /*
544 * Init the main event queue (ASSUMES it cannot fail).
545 */
546 if (SUCCEEDED (rc))
547 EventQueue::init();
548
549 return rc;
550}
551
552HRESULT Shutdown()
553{
554 HRESULT rc = S_OK;
555
556#if !defined (VBOX_WITH_XPCOM)
557
558 /* EventQueue::uninit reference counting fun. */
559 RTTHREAD hSelf = RTThreadSelf();
560 if ( hSelf == gCOMMainThread
561 && hSelf != NIL_RTTHREAD)
562 {
563 if (-- gCOMMainInitCount == 0)
564 {
565 EventQueue::uninit();
566 ASMAtomicWriteHandle (&gCOMMainThread, NIL_RTTHREAD);
567 }
568 }
569
570 CoUninitialize();
571
572#else /* !defined (VBOX_WITH_XPCOM) */
573
574 nsCOMPtr <nsIEventQueue> eventQ;
575 rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
576
577 if (NS_SUCCEEDED(rc) || rc == NS_ERROR_NOT_AVAILABLE)
578 {
579 /* NS_ERROR_NOT_AVAILABLE seems to mean that
580 * nsIEventQueue::StopAcceptingEvents() has been called (see
581 * nsEventQueueService.cpp). We hope that this error code always means
582 * just that in this case and assume that we're on the main thread
583 * (it's a kind of unexpected behavior if a non-main thread ever calls
584 * StopAcceptingEvents() on the main event queue). */
585
586 PRBool isOnMainThread = PR_FALSE;
587 if (NS_SUCCEEDED(rc))
588 {
589 rc = eventQ->IsOnCurrentThread (&isOnMainThread);
590 eventQ = nsnull; /* early release before shutdown */
591 }
592 else
593 {
594 isOnMainThread = PR_TRUE;
595 rc = NS_OK;
596 }
597
598 if (NS_SUCCEEDED(rc) && isOnMainThread)
599 {
600 /* only the main thread needs to uninitialize XPCOM and only if
601 * init counter drops to zero */
602 if (-- gXPCOMInitCount == 0)
603 {
604 EventQueue::uninit();
605 rc = NS_ShutdownXPCOM (nsnull);
606
607 /* This is a thread initialized XPCOM and set gIsXPCOMInitialized to
608 * true. Reset it back to false. */
609 bool wasInited = ASMAtomicXchgBool (&gIsXPCOMInitialized, false);
610 Assert (wasInited == true);
611 NOREF (wasInited);
612
613#if defined (XPCOM_GLUE)
614 XPCOMGlueShutdown();
615#endif
616 }
617 }
618 }
619
620#endif /* !defined (VBOX_WITH_XPCOM) */
621
622 AssertComRC (rc);
623
624 return rc;
625}
626
627} /* namespace com */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use