VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/init.cpp@ 44469

Last change on this file since 44469 was 44460, checked in by vboxsync, 12 years ago

build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 16.8 KB
Line 
1/* $Id: init.cpp 44460 2013-01-30 11:30:08Z vboxsync $ */
2/** @file
3 * IPRT - Init Ring-3.
4 */
5
6/*
7 * Copyright (C) 2006-2009 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. 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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP RTLOGGROUP_DEFAULT
32#include <iprt/types.h> /* darwin: UINT32_C and others. */
33
34#ifdef RT_OS_WINDOWS
35# include <process.h>
36# include <Windows.h>
37#else
38# include <unistd.h>
39# ifndef RT_OS_OS2
40# include <pthread.h>
41# include <signal.h>
42# include <errno.h>
43# define IPRT_USE_SIG_CHILD_DUMMY
44# endif
45#endif
46#ifdef RT_OS_OS2
47# include <InnoTekLIBC/fork.h>
48# define INCL_DOSMISC
49# include <os2.h>
50#endif
51#include <locale.h>
52
53#include <iprt/initterm.h>
54#include <iprt/asm.h>
55#include <iprt/assert.h>
56#include <iprt/err.h>
57#include <iprt/log.h>
58#include <iprt/mem.h>
59#include <iprt/path.h>
60#include <iprt/time.h>
61#include <iprt/string.h>
62#include <iprt/param.h>
63#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
64# include <iprt/file.h>
65# include <VBox/sup.h>
66#endif
67#include <stdlib.h>
68
69#include "internal/alignmentchecks.h"
70#include "internal/path.h"
71#include "internal/process.h"
72#include "internal/thread.h"
73#include "internal/thread.h"
74#include "internal/time.h"
75
76
77/*******************************************************************************
78* Global Variables *
79*******************************************************************************/
80/** The number of calls to RTR3Init*. */
81static int32_t volatile g_cUsers = 0;
82/** Whether we're currently initializing the IPRT. */
83static bool volatile g_fInitializing = false;
84
85/** The process path.
86 * This is used by RTPathExecDir and RTProcGetExecutablePath and set by rtProcInitName. */
87DECLHIDDEN(char) g_szrtProcExePath[RTPATH_MAX];
88/** The length of g_szrtProcExePath. */
89DECLHIDDEN(size_t) g_cchrtProcExePath;
90/** The length of directory path component of g_szrtProcExePath. */
91DECLHIDDEN(size_t) g_cchrtProcDir;
92/** The offset of the process name into g_szrtProcExePath. */
93DECLHIDDEN(size_t) g_offrtProcName;
94
95/** The argument count of the program. */
96static int g_crtArgs = -1;
97/** The arguments of the program (UTF-8). This is "leaked". */
98static char ** g_papszrtArgs;
99/** The original argument vector of the program. */
100static char ** g_papszrtOrgArgs;
101
102/** Are we running in unobtrusive mode? */
103static bool g_fUnobtrusive = false;
104
105/**
106 * Program start nanosecond TS.
107 */
108DECLHIDDEN(uint64_t) g_u64ProgramStartNanoTS;
109
110/**
111 * Program start microsecond TS.
112 */
113DECLHIDDEN(uint64_t) g_u64ProgramStartMicroTS;
114
115/**
116 * Program start millisecond TS.
117 */
118DECLHIDDEN(uint64_t) g_u64ProgramStartMilliTS;
119
120/**
121 * The process identifier of the running process.
122 */
123DECLHIDDEN(RTPROCESS) g_ProcessSelf = NIL_RTPROCESS;
124
125/**
126 * The current process priority.
127 */
128DECLHIDDEN(RTPROCPRIORITY) g_enmProcessPriority = RTPROCPRIORITY_DEFAULT;
129
130/**
131 * Set if the atexit callback has been called, i.e. indicating
132 * that the process is terminating.
133 */
134DECLHIDDEN(bool volatile) g_frtAtExitCalled = false;
135
136#ifdef IPRT_WITH_ALIGNMENT_CHECKS
137/**
138 * Whether alignment checks are enabled.
139 * This is set if the environment variable IPRT_ALIGNMENT_CHECKS is 1.
140 */
141RTDATADECL(bool) g_fRTAlignmentChecks = false;
142#endif
143
144
145/**
146 * atexit callback.
147 *
148 * This makes sure any loggers are flushed and will later also work the
149 * termination callback chain.
150 */
151static void rtR3ExitCallback(void)
152{
153 ASMAtomicWriteBool(&g_frtAtExitCalled, true);
154
155 if (g_cUsers > 0)
156 {
157 PRTLOGGER pLogger = RTLogGetDefaultInstance();
158 if (pLogger)
159 RTLogFlush(pLogger);
160
161 pLogger = RTLogRelDefaultInstance();
162 if (pLogger)
163 RTLogFlush(pLogger);
164 }
165}
166
167
168#ifndef RT_OS_WINDOWS
169/**
170 * Fork callback, child context.
171 */
172static void rtR3ForkChildCallback(void)
173{
174 g_ProcessSelf = getpid();
175}
176#endif /* RT_OS_WINDOWS */
177
178#ifdef RT_OS_OS2
179/** Fork completion callback for OS/2. Only called in the child. */
180static void rtR3ForkOs2ChildCompletionCallback(void *pvArg, int rc, __LIBC_FORKCTX enmCtx)
181{
182 Assert(enmCtx == __LIBC_FORK_CTX_CHILD); NOREF(enmCtx);
183 NOREF(pvArg);
184
185 if (!rc)
186 rtR3ForkChildCallback();
187}
188
189/** Low-level fork callback for OS/2. */
190int rtR3ForkOs2Child(__LIBC_PFORKHANDLE pForkHandle, __LIBC_FORKOP enmOperation)
191{
192 if (enmOperation == __LIBC_FORK_OP_EXEC_CHILD)
193 return pForkHandle->pfnCompletionCallback(pForkHandle, rtR3ForkOs2ChildCompletionCallback, NULL, __LIBC_FORK_CTX_CHILD);
194 return 0;
195}
196
197# define static static volatile /** @todo _FORK_CHILD1 causes unresolved externals in optimized builds. Fix macro. */
198_FORK_CHILD1(0, rtR3ForkOs2Child);
199# undef static
200#endif /* RT_OS_OS2 */
201
202
203
204/**
205 * Internal worker which initializes or re-initializes the
206 * program path, name and directory globals.
207 *
208 * @returns IPRT status code.
209 * @param pszProgramPath The program path, NULL if not specified.
210 */
211static int rtR3InitProgramPath(const char *pszProgramPath)
212{
213 /*
214 * We're reserving 32 bytes here for file names as what not.
215 */
216 if (!pszProgramPath)
217 {
218 int rc = rtProcInitExePath(g_szrtProcExePath, sizeof(g_szrtProcExePath) - 32);
219 if (RT_FAILURE(rc))
220 return rc;
221 }
222 else
223 {
224 size_t cch = strlen(pszProgramPath);
225 Assert(cch > 1);
226 AssertMsgReturn(cch < sizeof(g_szrtProcExePath) - 32, ("%zu\n", cch), VERR_BUFFER_OVERFLOW);
227 memcpy(g_szrtProcExePath, pszProgramPath, cch + 1);
228 }
229
230 /*
231 * Parse the name.
232 */
233 ssize_t offName;
234 g_cchrtProcExePath = RTPathParse(g_szrtProcExePath, &g_cchrtProcDir, &offName, NULL);
235 g_offrtProcName = offName;
236 return VINF_SUCCESS;
237}
238
239
240/**
241 * Internal worker which initializes or re-initializes the
242 * program path, name and directory globals.
243 *
244 * @returns IPRT status code.
245 * @param fFlags Flags, see RTR3INIT_XXX.
246 * @param cArgs Pointer to the argument count.
247 * @param ppapszArgs Pointer to the argument vector pointer. NULL
248 * allowed if @a cArgs is 0.
249 */
250static int rtR3InitArgv(uint32_t fFlags, int cArgs, char ***ppapszArgs)
251{
252 NOREF(fFlags);
253 if (cArgs)
254 {
255 AssertPtr(ppapszArgs);
256 AssertPtr(*ppapszArgs);
257 char **papszOrgArgs = *ppapszArgs;
258
259 /*
260 * Normally we should only be asked to convert arguments once. If we
261 * are though, it should be the already convered arguments.
262 */
263 if (g_crtArgs != -1)
264 {
265 AssertReturn( g_crtArgs == cArgs
266 && g_papszrtArgs == papszOrgArgs,
267 VERR_WRONG_ORDER); /* only init once! */
268 return VINF_SUCCESS;
269 }
270
271 /*
272 * Convert the arguments.
273 */
274 char **papszArgs = (char **)RTMemAllocZ((cArgs + 1) * sizeof(char *));
275 if (!papszArgs)
276 return VERR_NO_MEMORY;
277
278 for (int i = 0; i < cArgs; i++)
279 {
280 int rc = RTStrCurrentCPToUtf8(&papszArgs[i], papszOrgArgs[i]);
281 if (RT_FAILURE(rc))
282 {
283 while (i--)
284 RTStrFree(papszArgs[i]);
285 RTMemFree(papszArgs);
286 return rc;
287 }
288 }
289 papszArgs[cArgs] = NULL;
290
291 g_papszrtOrgArgs = papszOrgArgs;
292 g_papszrtArgs = papszArgs;
293 g_crtArgs = cArgs;
294
295 *ppapszArgs = papszArgs;
296 }
297
298 return VINF_SUCCESS;
299}
300
301
302#ifdef IPRT_USE_SIG_CHILD_DUMMY
303/**
304 * Dummy SIGCHILD handler.
305 *
306 * Assigned on rtR3Init only when SIGCHILD handler is set SIGIGN or SIGDEF to
307 * ensure waitpid works properly for the terminated processes.
308 */
309static void rtR3SigChildHandler(int iSignal)
310{
311 NOREF(iSignal);
312}
313#endif /* IPRT_USE_SIG_CHILD_DUMMY */
314
315
316/**
317 * rtR3Init worker.
318 */
319static int rtR3InitBody(uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
320{
321 /*
322 * Init C runtime locale before we do anything that may end up converting
323 * paths or we'll end up using the "C" locale for path conversion.
324 */
325 setlocale(LC_CTYPE, "");
326
327 /*
328 * The Process ID.
329 */
330#ifdef _MSC_VER
331 g_ProcessSelf = _getpid(); /* crappy ansi compiler */
332#else
333 g_ProcessSelf = getpid();
334#endif
335
336 /*
337 * Disable error popups.
338 */
339#ifdef RT_OS_WINDOWS
340 UINT fOldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
341 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX | fOldErrMode);
342#elif defined(RT_OS_OS2)
343 DosError(FERR_DISABLEHARDERR);
344#endif
345
346 g_fUnobtrusive = !!(fFlags & RTR3INIT_FLAGS_UNOBTRUSIVE);
347
348#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
349# ifdef VBOX
350 /*
351 * This MUST be done as the very first thing, before any file is opened.
352 * The log is opened on demand, but the first log entries may be caused
353 * by rtThreadInit() below.
354 */
355 const char *pszDisableHostCache = getenv("VBOX_DISABLE_HOST_DISK_CACHE");
356 if ( pszDisableHostCache != NULL
357 && *pszDisableHostCache
358 && strcmp(pszDisableHostCache, "0") != 0)
359 {
360 RTFileSetForceFlags(RTFILE_O_WRITE, RTFILE_O_WRITE_THROUGH, 0);
361 RTFileSetForceFlags(RTFILE_O_READWRITE, RTFILE_O_WRITE_THROUGH, 0);
362 }
363# endif /* VBOX */
364#endif /* !IN_GUEST && !RT_NO_GIP */
365
366 /*
367 * Thread Thread database and adopt the caller thread as 'main'.
368 * This must be done before everything else or else we'll call into threading
369 * without having initialized TLS entries and suchlike.
370 */
371 int rc = rtThreadInit();
372 AssertMsgRCReturn(rc, ("Failed to initialize threads, rc=%Rrc!\n", rc), rc);
373
374#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
375 if (fFlags & RTR3INIT_FLAGS_SUPLIB)
376 {
377 /*
378 * Init GIP first.
379 * (The more time for updates before real use, the better.)
380 */
381 rc = SUPR3Init(NULL);
382 AssertMsgRCReturn(rc, ("Failed to initializable the support library, rc=%Rrc!\n", rc), rc);
383 }
384#endif
385
386 /*
387 * The executable path, name and directory. Convert arguments.
388 */
389 rc = rtR3InitProgramPath(pszProgramPath);
390 AssertLogRelMsgRCReturn(rc, ("Failed to get executable directory path, rc=%Rrc!\n", rc), rc);
391
392 rc = rtR3InitArgv(fFlags, cArgs, papszArgs);
393 AssertLogRelMsgRCReturn(rc, ("Failed to convert the arguments, rc=%Rrc!\n", rc), rc);
394
395#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
396 /*
397 * The threading is initialized we can safely sleep a bit if GIP
398 * needs some time to update itself updating.
399 */
400 if ((fFlags & RTR3INIT_FLAGS_SUPLIB) && g_pSUPGlobalInfoPage)
401 {
402 RTThreadSleep(20);
403 RTTimeNanoTS();
404 }
405#endif
406
407 /*
408 * Init the program start TSes.
409 * Do that here to be sure that the GIP time was properly updated the 1st time.
410 */
411 g_u64ProgramStartNanoTS = RTTimeNanoTS();
412 g_u64ProgramStartMicroTS = g_u64ProgramStartNanoTS / 1000;
413 g_u64ProgramStartMilliTS = g_u64ProgramStartNanoTS / 1000000;
414
415 /*
416 * The remainder cannot easily be undone, so it has to go last.
417 */
418
419 /* Fork and exit callbacks. */
420#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
421 rc = pthread_atfork(NULL, NULL, rtR3ForkChildCallback);
422 AssertMsg(rc == 0, ("%d\n", rc));
423#endif
424 atexit(rtR3ExitCallback);
425
426#ifdef IPRT_USE_SIG_CHILD_DUMMY
427 /*
428 * SIGCHLD must not be ignored (that's default), otherwise posix compliant waitpid
429 * implementations won't work right.
430 */
431 for (;;)
432 {
433 struct sigaction saOld;
434 rc = sigaction(SIGCHLD, 0, &saOld); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
435 if ( rc != 0
436 || (saOld.sa_flags & SA_SIGINFO)
437 || ( saOld.sa_handler != SIG_IGN
438 && saOld.sa_handler != SIG_DFL)
439 )
440 break;
441
442 /* Try install dummy handler. */
443 struct sigaction saNew = saOld;
444 saNew.sa_flags = SA_NOCLDSTOP | SA_RESTART;
445 saNew.sa_handler = rtR3SigChildHandler;
446 rc = sigemptyset(&saNew.sa_mask); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
447 struct sigaction saOld2;
448 rc = sigaction(SIGCHLD, &saNew, &saOld2); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
449 if ( rc != 0
450 || ( saOld2.sa_handler == saOld.sa_handler
451 && !(saOld2.sa_flags & SA_SIGINFO))
452 )
453 break;
454
455 /* Race during dynamic load, restore and try again... */
456 sigaction(SIGCHLD, &saOld2, NULL);
457 RTThreadYield();
458 }
459#endif /* IPRT_USE_SIG_CHILD_DUMMY */
460
461#ifdef IPRT_WITH_ALIGNMENT_CHECKS
462 /*
463 * Enable alignment checks.
464 */
465 const char *pszAlignmentChecks = getenv("IPRT_ALIGNMENT_CHECKS");
466 g_fRTAlignmentChecks = pszAlignmentChecks != NULL
467 && pszAlignmentChecks[0] == '1'
468 && pszAlignmentChecks[1] == '\0';
469 if (g_fRTAlignmentChecks)
470 IPRT_ALIGNMENT_CHECKS_ENABLE();
471#endif
472
473 return VINF_SUCCESS;
474}
475
476
477/**
478 * Internal initialization worker.
479 *
480 * @returns IPRT status code.
481 * @param fFlags Flags, see RTR3INIT_XXX.
482 * @param cArgs Pointer to the argument count.
483 * @param ppapszArgs Pointer to the argument vector pointer. NULL
484 * allowed if @a cArgs is 0.
485 * @param pszProgramPath The program path. Pass NULL if we're to figure it
486 * out ourselves.
487 */
488static int rtR3Init(uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
489{
490 /* no entry log flow, because prefixes and thread may freak out. */
491 Assert(!(fFlags & ~( RTR3INIT_FLAGS_DLL
492 | RTR3INIT_FLAGS_SUPLIB
493 | RTR3INIT_FLAGS_UNOBTRUSIVE)));
494 Assert(!(fFlags & RTR3INIT_FLAGS_DLL) || cArgs == 0);
495
496 /*
497 * Do reference counting, only initialize the first time around.
498 *
499 * We are ASSUMING that nobody will be able to race RTR3Init* calls when the
500 * first one, the real init, is running (second assertion).
501 */
502 int32_t cUsers = ASMAtomicIncS32(&g_cUsers);
503 if (cUsers != 1)
504 {
505 AssertMsg(cUsers > 1, ("%d\n", cUsers));
506 Assert(!g_fInitializing);
507#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
508 if (fFlags & RTR3INIT_FLAGS_SUPLIB)
509 SUPR3Init(NULL);
510#endif
511 if (!pszProgramPath)
512 return VINF_SUCCESS;
513
514 int rc = rtR3InitProgramPath(pszProgramPath);
515 if (RT_SUCCESS(rc))
516 rc = rtR3InitArgv(fFlags, cArgs, papszArgs);
517 return rc;
518 }
519 ASMAtomicWriteBool(&g_fInitializing, true);
520
521 /*
522 * Do the initialization.
523 */
524 int rc = rtR3InitBody(fFlags, cArgs, papszArgs, pszProgramPath);
525 if (RT_FAILURE(rc))
526 {
527 /* failure */
528 ASMAtomicWriteBool(&g_fInitializing, false);
529 ASMAtomicDecS32(&g_cUsers);
530 return rc;
531 }
532
533 /* success */
534 LogFlow(("rtR3Init: returns VINF_SUCCESS\n"));
535 ASMAtomicWriteBool(&g_fInitializing, false);
536 return VINF_SUCCESS;
537}
538
539
540RTR3DECL(int) RTR3InitExe(int cArgs, char ***papszArgs, uint32_t fFlags)
541{
542 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
543 return rtR3Init(fFlags, cArgs, papszArgs, NULL);
544}
545
546
547RTR3DECL(int) RTR3InitExeNoArguments(uint32_t fFlags)
548{
549 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
550 return rtR3Init(fFlags, 0, NULL, NULL);
551}
552
553
554RTR3DECL(int) RTR3InitDll(uint32_t fFlags)
555{
556 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
557 return rtR3Init(fFlags | RTR3INIT_FLAGS_DLL, 0, NULL, NULL);
558}
559
560
561RTR3DECL(int) RTR3InitEx(uint32_t iVersion, uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
562{
563 AssertReturn(iVersion == RTR3INIT_VER_CUR, VERR_NOT_SUPPORTED);
564 return rtR3Init(fFlags, cArgs, papszArgs, pszProgramPath);
565}
566
567RTR3DECL(bool) RTR3InitIsUnobtrusive(void)
568{
569 return g_fUnobtrusive;
570}
571
572#if 0 /** @todo implement RTR3Term. */
573RTR3DECL(void) RTR3Term(void)
574{
575}
576#endif
577
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