VirtualBox

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

Last change on this file since 17636 was 16674, checked in by vboxsync, 16 years ago

Main/Glue: com::Initialize(): Cleanup a failed XPCOM initialization before trying with a new path.

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

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