VirtualBox

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

Last change on this file since 16560 was 16555, checked in by vboxsync, 15 years ago

export

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.3 KB
Line 
1/* $Id: initterm.cpp 16555 2009-02-06 16:21:41Z 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
196HRESULT Initialize()
197{
198 HRESULT rc = E_FAIL;
199
200#if !defined (VBOX_WITH_XPCOM)
201
202 DWORD flags = COINIT_MULTITHREADED |
203 COINIT_DISABLE_OLE1DDE |
204 COINIT_SPEED_OVER_MEMORY;
205
206 rc = CoInitializeEx (NULL, flags);
207
208 /// @todo the below rough method of changing the aparment type doesn't
209 /// work on some systems for unknown reason (CoUninitialize() simply does
210 /// nothing there, or at least all 10 000 of subsequent CoInitializeEx()
211 /// continue to return RPC_E_CHANGED_MODE there). The problem on those
212 /// systems is related to the "Extend support for advanced text services
213 /// to all programs" checkbox in the advanced language settings dialog,
214 /// i.e. the problem appears when this checkbox is checked and disappears
215 /// if you clear it. For this reason, we disable the code below and
216 /// instead initialize COM in MTA as early as possible, before 3rd party
217 /// libraries we use have done so (i.e. Qt).
218#if 0
219 /* If we fail to set the necessary apartment model, it may mean that some
220 * DLL that was indirectly loaded by the process calling this function has
221 * already initialized COM on the given thread in an incompatible way
222 * which we can't leave with. Therefore, we try to fix this by using the
223 * brute force method: */
224
225 if (rc == RPC_E_CHANGED_MODE)
226 {
227 /* Before we use brute force, we need to check if we are in the
228 * neutral threaded apartment -- in this case there is no need to
229 * worry at all. */
230
231 rc = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);
232 if (rc == RPC_E_CHANGED_MODE)
233 {
234 /* This is a neutral apartment, reset the error */
235 rc = S_OK;
236
237 LogFlowFunc (("COM is already initialized in neutral threaded "
238 "apartment mode,\nwill accept it.\n"));
239 }
240 else if (rc == S_FALSE)
241 {
242 /* balance the test CoInitializeEx above */
243 CoUninitialize();
244 rc = RPC_E_CHANGED_MODE;
245
246 LogFlowFunc (("COM is already initialized in single threaded "
247 "apartment mode,\nwill reinitialize as "
248 "multi threaded.\n"));
249
250 enum { MaxTries = 10000 };
251 int tries = MaxTries;
252 while (rc == RPC_E_CHANGED_MODE && tries --)
253 {
254 CoUninitialize();
255 rc = CoInitializeEx (NULL, flags);
256 if (rc == S_OK)
257 {
258 /* We've successfully reinitialized COM; restore the
259 * initialization reference counter */
260
261 LogFlowFunc (("Will call CoInitializeEx() %d times.\n",
262 MaxTries - tries));
263
264 while (tries ++ < MaxTries)
265 {
266 rc = CoInitializeEx (NULL, flags);
267 Assert (rc == S_FALSE);
268 }
269 }
270 }
271 }
272 else
273 AssertMsgFailed (("rc=%08X\n", rc));
274 }
275#endif
276
277 /* the overall result must be either S_OK or S_FALSE (S_FALSE means
278 * "already initialized using the same apartment model") */
279 AssertMsg (rc == S_OK || rc == S_FALSE, ("rc=%08X\n", rc));
280
281#else /* !defined (VBOX_WITH_XPCOM) */
282
283 if (ASMAtomicXchgBool (&gIsXPCOMInitialized, true) == true)
284 {
285 /* XPCOM is already initialized on the main thread, no special
286 * initialization is necessary on additional threads. Just increase
287 * the init counter if it's a main thread again (to correctly support
288 * nested calls to Initialize()/Shutdown() for compatibility with
289 * Win32). */
290
291 nsCOMPtr <nsIEventQueue> eventQ;
292 rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
293
294 if (NS_SUCCEEDED (rc))
295 {
296 PRBool isOnMainThread = PR_FALSE;
297 rc = eventQ->IsOnCurrentThread (&isOnMainThread);
298 if (NS_SUCCEEDED (rc) && isOnMainThread)
299 ++ gXPCOMInitCount;
300 }
301
302 AssertComRC (rc);
303 return rc;
304 }
305
306 /* this is the first initialization */
307 gXPCOMInitCount = 1;
308
309 /* Set VBOX_XPCOM_HOME if not present */
310 if (!RTEnvExist ("VBOX_XPCOM_HOME"))
311 {
312 /* get the executable path */
313 char pathProgram [RTPATH_MAX];
314 int vrc = RTPathProgram (pathProgram, sizeof (pathProgram));
315 if (RT_SUCCESS (vrc))
316 {
317 char *pathProgramCP = NULL;
318 vrc = RTStrUtf8ToCurrentCP (&pathProgramCP, pathProgram);
319 if (RT_SUCCESS (vrc))
320 {
321 vrc = RTEnvSet ("VBOX_XPCOM_HOME", pathProgramCP);
322 RTStrFree (pathProgramCP);
323 }
324 }
325 AssertRC (vrc);
326 }
327
328#if defined (XPCOM_GLUE)
329 XPCOMGlueStartup (nsnull);
330#endif
331
332 nsCOMPtr <DirectoryServiceProvider> dsProv;
333
334 /* prepare paths for registry files */
335 char homeDir [RTPATH_MAX];
336 char privateArchDir [RTPATH_MAX];
337 int vrc = GetVBoxUserHomeDirectory (homeDir, sizeof (homeDir));
338 if (RT_SUCCESS (vrc))
339 vrc = RTPathAppPrivateArch (privateArchDir, sizeof (privateArchDir));
340 if (RT_SUCCESS (vrc))
341 {
342 char compReg [RTPATH_MAX];
343 char xptiDat [RTPATH_MAX];
344 char compDir [RTPATH_MAX];
345
346 RTStrPrintf (compReg, sizeof (compReg), "%s%c%s",
347 homeDir, RTPATH_DELIMITER, "compreg.dat");
348 RTStrPrintf (xptiDat, sizeof (xptiDat), "%s%c%s",
349 homeDir, RTPATH_DELIMITER, "xpti.dat");
350 RTStrPrintf (compDir, sizeof (compDir), "%s%c%s",
351 privateArchDir, RTPATH_DELIMITER, "components");
352
353 LogFlowFunc (("component registry : \"%s\"\n", compReg));
354 LogFlowFunc (("XPTI data file : \"%s\"\n", xptiDat));
355 LogFlowFunc (("component directory : \"%s\"\n", compDir));
356
357 dsProv = new DirectoryServiceProvider();
358 if (dsProv)
359 rc = dsProv->init (compReg, xptiDat, compDir, privateArchDir);
360 else
361 rc = NS_ERROR_OUT_OF_MEMORY;
362 }
363 else
364 rc = NS_ERROR_FAILURE;
365
366 if (NS_SUCCEEDED (rc))
367 {
368 /* get the path to the executable */
369 nsCOMPtr <nsIFile> appDir;
370 {
371 char path [RTPATH_MAX];
372 char *appDirCP = NULL;
373#if defined (DEBUG)
374 const char *env = RTEnvGet ("VIRTUALBOX_APP_HOME");
375 if (env)
376 {
377 char *appDirUtf8 = NULL;
378 vrc = RTStrCurrentCPToUtf8 (&appDirUtf8, env);
379 if (RT_SUCCESS (vrc))
380 {
381 vrc = RTPathReal (appDirUtf8, path, RTPATH_MAX);
382 if (RT_SUCCESS (vrc))
383 vrc = RTStrUtf8ToCurrentCP (&appDirCP, appDirUtf8);
384 RTStrFree (appDirUtf8);
385 }
386 }
387 else
388#endif
389 {
390 vrc = RTPathProgram (path, RTPATH_MAX);
391 if (RT_SUCCESS (vrc))
392 vrc = RTStrUtf8ToCurrentCP (&appDirCP, path);
393 }
394
395 if (RT_SUCCESS (vrc))
396 {
397 nsCOMPtr <nsILocalFile> file;
398 rc = NS_NewNativeLocalFile (nsEmbedCString (appDirCP),
399 PR_FALSE, getter_AddRefs (file));
400 if (NS_SUCCEEDED (rc))
401 appDir = do_QueryInterface (file, &rc);
402
403 RTStrFree (appDirCP);
404 }
405 else
406 rc = NS_ERROR_FAILURE;
407 }
408
409 /* Finally, initialize XPCOM */
410 if (NS_SUCCEEDED (rc))
411 {
412 nsCOMPtr <nsIServiceManager> serviceManager;
413 rc = NS_InitXPCOM2 (getter_AddRefs (serviceManager),
414 appDir, dsProv);
415
416 if (NS_SUCCEEDED (rc))
417 {
418 nsCOMPtr <nsIComponentRegistrar> registrar =
419 do_QueryInterface (serviceManager, &rc);
420 if (NS_SUCCEEDED (rc))
421 registrar->AutoRegister (nsnull);
422 }
423 }
424 }
425
426#endif /* !defined (VBOX_WITH_XPCOM) */
427
428 AssertComRC (rc);
429
430 return rc;
431}
432
433HRESULT Shutdown()
434{
435 HRESULT rc = S_OK;
436
437#if !defined (VBOX_WITH_XPCOM)
438
439 CoUninitialize();
440
441#else /* !defined (VBOX_WITH_XPCOM) */
442
443 nsCOMPtr <nsIEventQueue> eventQ;
444 rc = NS_GetMainEventQ (getter_AddRefs (eventQ));
445
446 if (NS_SUCCEEDED (rc) || rc == NS_ERROR_NOT_AVAILABLE)
447 {
448 /* NS_ERROR_NOT_AVAILABLE seems to mean that
449 * nsIEventQueue::StopAcceptingEvents() has been called (see
450 * nsEventQueueService.cpp). We hope that this error code always means
451 * just that in this case and assume that we're on the main thread
452 * (it's a kind of unexpected behavior if a non-main thread ever calls
453 * StopAcceptingEvents() on the main event queue). */
454
455 PRBool isOnMainThread = PR_FALSE;
456 if (NS_SUCCEEDED (rc))
457 {
458 rc = eventQ->IsOnCurrentThread (&isOnMainThread);
459 eventQ = nsnull; /* early release before shutdown */
460 }
461 else
462 {
463 isOnMainThread = PR_TRUE;
464 rc = NS_OK;
465 }
466
467 if (NS_SUCCEEDED (rc) && isOnMainThread)
468 {
469 /* only the main thread needs to uninitialize XPCOM and only if
470 * init counter drops to zero */
471 if (-- gXPCOMInitCount == 0)
472 {
473 rc = NS_ShutdownXPCOM (nsnull);
474
475 /* This is a thread initialized XPCOM and set gIsXPCOMInitialized to
476 * true. Reset it back to false. */
477 bool wasInited = ASMAtomicXchgBool (&gIsXPCOMInitialized, false);
478 Assert (wasInited == true);
479 NOREF (wasInited);
480
481#if defined (XPCOM_GLUE)
482 XPCOMGlueShutdown();
483#endif
484 }
485 }
486 }
487
488#endif /* !defined (VBOX_WITH_XPCOM) */
489
490 AssertComRC (rc);
491
492 return rc;
493}
494
495} /* namespace com */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use