VirtualBox

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

Last change on this file since 46668 was 46593, checked in by vboxsync, 11 years ago

updates

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.9 KB
Line 
1/* $Id: init.cpp 46593 2013-06-17 14:32:51Z vboxsync $ */
2/** @file
3 * IPRT - Init Ring-3.
4 */
5
6/*
7 * Copyright (C) 2006-2013 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 "init.h"
70#include "internal/alignmentchecks.h"
71#include "internal/path.h"
72#include "internal/process.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 IPRT init flags. */
96static uint32_t g_fInitFlags;
97
98/** The argument count of the program. */
99static int g_crtArgs = -1;
100/** The arguments of the program (UTF-8). This is "leaked". */
101static char ** g_papszrtArgs;
102/** The original argument vector of the program. */
103static char ** g_papszrtOrgArgs;
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#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) || defined(RT_OS_HAIKU) \
146 || defined(RT_OS_LINUX) || defined(RT_OS_OS2) || defined(RT_OS_SOLARIS) /** @todo add host init hooks everywhere. */
147/* Stubs */
148DECLHIDDEN(int) rtR3InitNativeFirst(uint32_t fFlags) { return VINF_SUCCESS; }
149DECLHIDDEN(int) rtR3InitNativeFinal(uint32_t fFlags) { return VINF_SUCCESS; }
150DECLHIDDEN(void) rtR3InitNativeObtrusive(void) { }
151#endif
152
153
154/**
155 * atexit callback.
156 *
157 * This makes sure any loggers are flushed and will later also work the
158 * termination callback chain.
159 */
160static void rtR3ExitCallback(void)
161{
162 ASMAtomicWriteBool(&g_frtAtExitCalled, true);
163
164 if (g_cUsers > 0)
165 {
166 PRTLOGGER pLogger = RTLogGetDefaultInstance();
167 if (pLogger)
168 RTLogFlush(pLogger);
169
170 pLogger = RTLogRelDefaultInstance();
171 if (pLogger)
172 RTLogFlush(pLogger);
173 }
174}
175
176
177#ifndef RT_OS_WINDOWS
178/**
179 * Fork callback, child context.
180 */
181static void rtR3ForkChildCallback(void)
182{
183 g_ProcessSelf = getpid();
184}
185#endif /* RT_OS_WINDOWS */
186
187#ifdef RT_OS_OS2
188/** Fork completion callback for OS/2. Only called in the child. */
189static void rtR3ForkOs2ChildCompletionCallback(void *pvArg, int rc, __LIBC_FORKCTX enmCtx)
190{
191 Assert(enmCtx == __LIBC_FORK_CTX_CHILD); NOREF(enmCtx);
192 NOREF(pvArg);
193
194 if (!rc)
195 rtR3ForkChildCallback();
196}
197
198/** Low-level fork callback for OS/2. */
199int rtR3ForkOs2Child(__LIBC_PFORKHANDLE pForkHandle, __LIBC_FORKOP enmOperation)
200{
201 if (enmOperation == __LIBC_FORK_OP_EXEC_CHILD)
202 return pForkHandle->pfnCompletionCallback(pForkHandle, rtR3ForkOs2ChildCompletionCallback, NULL, __LIBC_FORK_CTX_CHILD);
203 return 0;
204}
205
206# define static static volatile /** @todo _FORK_CHILD1 causes unresolved externals in optimized builds. Fix macro. */
207_FORK_CHILD1(0, rtR3ForkOs2Child);
208# undef static
209#endif /* RT_OS_OS2 */
210
211
212
213/**
214 * Internal worker which initializes or re-initializes the
215 * program path, name and directory globals.
216 *
217 * @returns IPRT status code.
218 * @param pszProgramPath The program path, NULL if not specified.
219 */
220static int rtR3InitProgramPath(const char *pszProgramPath)
221{
222 /*
223 * We're reserving 32 bytes here for file names as what not.
224 */
225 if (!pszProgramPath)
226 {
227 int rc = rtProcInitExePath(g_szrtProcExePath, sizeof(g_szrtProcExePath) - 32);
228 if (RT_FAILURE(rc))
229 return rc;
230 }
231 else
232 {
233 size_t cch = strlen(pszProgramPath);
234 Assert(cch > 1);
235 AssertMsgReturn(cch < sizeof(g_szrtProcExePath) - 32, ("%zu\n", cch), VERR_BUFFER_OVERFLOW);
236 memcpy(g_szrtProcExePath, pszProgramPath, cch + 1);
237 }
238
239 /*
240 * Parse the name.
241 */
242 ssize_t offName;
243 g_cchrtProcExePath = RTPathParseSimple(g_szrtProcExePath, &g_cchrtProcDir, &offName, NULL);
244 g_offrtProcName = offName;
245 return VINF_SUCCESS;
246}
247
248
249/**
250 * Internal worker which initializes or re-initializes the
251 * program path, name and directory globals.
252 *
253 * @returns IPRT status code.
254 * @param fFlags Flags, see RTR3INIT_XXX.
255 * @param cArgs Pointer to the argument count.
256 * @param ppapszArgs Pointer to the argument vector pointer. NULL
257 * allowed if @a cArgs is 0.
258 */
259static int rtR3InitArgv(uint32_t fFlags, int cArgs, char ***ppapszArgs)
260{
261 NOREF(fFlags);
262 if (cArgs)
263 {
264 AssertPtr(ppapszArgs);
265 AssertPtr(*ppapszArgs);
266 char **papszOrgArgs = *ppapszArgs;
267
268 /*
269 * Normally we should only be asked to convert arguments once. If we
270 * are though, it should be the already convered arguments.
271 */
272 if (g_crtArgs != -1)
273 {
274 AssertReturn( g_crtArgs == cArgs
275 && g_papszrtArgs == papszOrgArgs,
276 VERR_WRONG_ORDER); /* only init once! */
277 return VINF_SUCCESS;
278 }
279
280 /*
281 * Convert the arguments.
282 */
283 char **papszArgs = (char **)RTMemAllocZ((cArgs + 1) * sizeof(char *));
284 if (!papszArgs)
285 return VERR_NO_MEMORY;
286
287#ifdef RT_OS_WINDOWS
288 /* HACK ALERT! Try convert from unicode versions if possible.
289 Unfortunately for us, __wargv is only initialized if we have a
290 unicode main function. So, we have to use CommandLineToArgvW to get
291 something similar. It should do the same conversion... :-) */
292 int cArgsW = -1;
293 PWSTR *papwszArgs = NULL;
294 if ( papszOrgArgs == __argv
295 && cArgs == __argc
296 && (papwszArgs = CommandLineToArgvW(GetCommandLineW(), &cArgsW)) != NULL )
297 {
298 AssertMsg(cArgsW == cArgs, ("%d vs %d\n", cArgsW, cArgs));
299 for (int i = 0; i < cArgs; i++)
300 {
301 int rc = RTUtf16ToUtf8(papwszArgs[i], &papszArgs[i]);
302 if (RT_FAILURE(rc))
303 {
304 while (i--)
305 RTStrFree(papszArgs[i]);
306 RTMemFree(papszArgs);
307 LocalFree(papwszArgs);
308 return rc;
309 }
310 }
311 LocalFree(papwszArgs);
312 }
313 else
314#endif
315 {
316 for (int i = 0; i < cArgs; i++)
317 {
318 int rc = RTStrCurrentCPToUtf8(&papszArgs[i], papszOrgArgs[i]);
319 if (RT_FAILURE(rc))
320 {
321 while (i--)
322 RTStrFree(papszArgs[i]);
323 RTMemFree(papszArgs);
324 return rc;
325 }
326 }
327 }
328
329 papszArgs[cArgs] = NULL;
330
331 g_papszrtOrgArgs = papszOrgArgs;
332 g_papszrtArgs = papszArgs;
333 g_crtArgs = cArgs;
334
335 *ppapszArgs = papszArgs;
336 }
337
338 return VINF_SUCCESS;
339}
340
341
342#ifdef IPRT_USE_SIG_CHILD_DUMMY
343/**
344 * Dummy SIGCHILD handler.
345 *
346 * Assigned on rtR3Init only when SIGCHILD handler is set SIGIGN or SIGDEF to
347 * ensure waitpid works properly for the terminated processes.
348 */
349static void rtR3SigChildHandler(int iSignal)
350{
351 NOREF(iSignal);
352}
353#endif /* IPRT_USE_SIG_CHILD_DUMMY */
354
355
356/**
357 * rtR3Init worker.
358 */
359static int rtR3InitBody(uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
360{
361 /*
362 * Early native initialization.
363 */
364 int rc = rtR3InitNativeFirst(fFlags);
365 AssertMsgRCReturn(rc, ("rtR3InitNativeFirst failed with %Rrc\n", rc), rc);
366
367 /*
368 * Disable error popups.
369 */
370#if defined(RT_OS_OS2) /** @todo move to private code. */
371 DosError(FERR_DISABLEHARDERR);
372#endif
373
374 /*
375 * Init C runtime locale before we do anything that may end up converting
376 * paths or we'll end up using the "C" locale for path conversion.
377 */
378 setlocale(LC_CTYPE, "");
379
380 /*
381 * The Process ID.
382 */
383#ifdef _MSC_VER
384 g_ProcessSelf = _getpid(); /* crappy ansi compiler */
385#else
386 g_ProcessSelf = getpid();
387#endif
388
389 /*
390 * Save the init flags.
391 */
392 g_fInitFlags |= fFlags;
393
394#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
395# ifdef VBOX
396 /*
397 * This MUST be done as the very first thing, before any file is opened.
398 * The log is opened on demand, but the first log entries may be caused
399 * by rtThreadInit() below.
400 */
401 const char *pszDisableHostCache = getenv("VBOX_DISABLE_HOST_DISK_CACHE");
402 if ( pszDisableHostCache != NULL
403 && *pszDisableHostCache
404 && strcmp(pszDisableHostCache, "0") != 0)
405 {
406 RTFileSetForceFlags(RTFILE_O_WRITE, RTFILE_O_WRITE_THROUGH, 0);
407 RTFileSetForceFlags(RTFILE_O_READWRITE, RTFILE_O_WRITE_THROUGH, 0);
408 }
409# endif /* VBOX */
410#endif /* !IN_GUEST && !RT_NO_GIP */
411
412 /*
413 * Thread Thread database and adopt the caller thread as 'main'.
414 * This must be done before everything else or else we'll call into threading
415 * without having initialized TLS entries and suchlike.
416 */
417 rc = rtThreadInit();
418 AssertMsgRCReturn(rc, ("Failed to initialize threads, rc=%Rrc!\n", rc), rc);
419
420#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
421 if (fFlags & RTR3INIT_FLAGS_SUPLIB)
422 {
423 /*
424 * Init GIP first.
425 * (The more time for updates before real use, the better.)
426 */
427 rc = SUPR3Init(NULL);
428 AssertMsgRCReturn(rc, ("Failed to initializable the support library, rc=%Rrc!\n", rc), rc);
429 }
430#endif
431
432 /*
433 * The executable path, name and directory. Convert arguments.
434 */
435 rc = rtR3InitProgramPath(pszProgramPath);
436 AssertLogRelMsgRCReturn(rc, ("Failed to get executable directory path, rc=%Rrc!\n", rc), rc);
437
438 rc = rtR3InitArgv(fFlags, cArgs, papszArgs);
439 AssertLogRelMsgRCReturn(rc, ("Failed to convert the arguments, rc=%Rrc!\n", rc), rc);
440
441#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
442 /*
443 * The threading is initialized we can safely sleep a bit if GIP
444 * needs some time to update itself updating.
445 */
446 if ((fFlags & RTR3INIT_FLAGS_SUPLIB) && g_pSUPGlobalInfoPage)
447 {
448 RTThreadSleep(20);
449 RTTimeNanoTS();
450 }
451#endif
452
453 /*
454 * Init the program start TSes.
455 * Do that here to be sure that the GIP time was properly updated the 1st time.
456 */
457 g_u64ProgramStartNanoTS = RTTimeNanoTS();
458 g_u64ProgramStartMicroTS = g_u64ProgramStartNanoTS / 1000;
459 g_u64ProgramStartMilliTS = g_u64ProgramStartNanoTS / 1000000;
460
461 /*
462 * The remainder cannot easily be undone, so it has to go last.
463 */
464
465 /* Fork and exit callbacks. */
466#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
467 rc = pthread_atfork(NULL, NULL, rtR3ForkChildCallback);
468 AssertMsg(rc == 0, ("%d\n", rc));
469#endif
470 atexit(rtR3ExitCallback);
471
472#ifdef IPRT_USE_SIG_CHILD_DUMMY
473 /*
474 * SIGCHLD must not be ignored (that's default), otherwise posix compliant waitpid
475 * implementations won't work right.
476 */
477 for (;;)
478 {
479 struct sigaction saOld;
480 rc = sigaction(SIGCHLD, 0, &saOld); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
481 if ( rc != 0
482 || (saOld.sa_flags & SA_SIGINFO)
483 || ( saOld.sa_handler != SIG_IGN
484 && saOld.sa_handler != SIG_DFL)
485 )
486 break;
487
488 /* Try install dummy handler. */
489 struct sigaction saNew = saOld;
490 saNew.sa_flags = SA_NOCLDSTOP | SA_RESTART;
491 saNew.sa_handler = rtR3SigChildHandler;
492 rc = sigemptyset(&saNew.sa_mask); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
493 struct sigaction saOld2;
494 rc = sigaction(SIGCHLD, &saNew, &saOld2); AssertMsg(rc == 0, ("%d/%d\n", rc, errno));
495 if ( rc != 0
496 || ( saOld2.sa_handler == saOld.sa_handler
497 && !(saOld2.sa_flags & SA_SIGINFO))
498 )
499 break;
500
501 /* Race during dynamic load, restore and try again... */
502 sigaction(SIGCHLD, &saOld2, NULL);
503 RTThreadYield();
504 }
505#endif /* IPRT_USE_SIG_CHILD_DUMMY */
506
507#ifdef IPRT_WITH_ALIGNMENT_CHECKS
508 /*
509 * Enable alignment checks.
510 */
511 const char *pszAlignmentChecks = getenv("IPRT_ALIGNMENT_CHECKS");
512 g_fRTAlignmentChecks = pszAlignmentChecks != NULL
513 && pszAlignmentChecks[0] == '1'
514 && pszAlignmentChecks[1] == '\0';
515 if (g_fRTAlignmentChecks)
516 IPRT_ALIGNMENT_CHECKS_ENABLE();
517#endif
518
519 /*
520 * Final native initialization.
521 */
522 rc = rtR3InitNativeFinal(fFlags);
523 AssertMsgRCReturn(rc, ("rtR3InitNativeFinal failed with %Rrc\n", rc), rc);
524
525 return VINF_SUCCESS;
526}
527
528
529/**
530 * Internal initialization worker.
531 *
532 * @returns IPRT status code.
533 * @param fFlags Flags, see RTR3INIT_XXX.
534 * @param cArgs Pointer to the argument count.
535 * @param ppapszArgs Pointer to the argument vector pointer. NULL
536 * allowed if @a cArgs is 0.
537 * @param pszProgramPath The program path. Pass NULL if we're to figure it
538 * out ourselves.
539 */
540static int rtR3Init(uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
541{
542 /* no entry log flow, because prefixes and thread may freak out. */
543 Assert(!(fFlags & ~( RTR3INIT_FLAGS_DLL
544 | RTR3INIT_FLAGS_SUPLIB
545 | RTR3INIT_FLAGS_UNOBTRUSIVE)));
546 Assert(!(fFlags & RTR3INIT_FLAGS_DLL) || cArgs == 0);
547
548 /*
549 * Do reference counting, only initialize the first time around.
550 *
551 * We are ASSUMING that nobody will be able to race RTR3Init* calls when the
552 * first one, the real init, is running (second assertion).
553 */
554 int32_t cUsers = ASMAtomicIncS32(&g_cUsers);
555 if (cUsers != 1)
556 {
557 AssertMsg(cUsers > 1, ("%d\n", cUsers));
558 Assert(!g_fInitializing);
559#if !defined(IN_GUEST) && !defined(RT_NO_GIP)
560 if (fFlags & RTR3INIT_FLAGS_SUPLIB)
561 {
562 SUPR3Init(NULL);
563 g_fInitFlags |= RTR3INIT_FLAGS_SUPLIB;
564 }
565#endif
566
567 if ( !(fFlags & RTR3INIT_FLAGS_UNOBTRUSIVE)
568 && (g_fInitFlags & RTR3INIT_FLAGS_UNOBTRUSIVE))
569 {
570 g_fInitFlags &= ~RTR3INIT_FLAGS_UNOBTRUSIVE;
571 rtR3InitNativeObtrusive();
572 rtThreadReInitObtrusive();
573 }
574
575 int rc = VINF_SUCCESS;
576 if (pszProgramPath)
577 rc = rtR3InitProgramPath(pszProgramPath);
578 if (RT_SUCCESS(rc))
579 rc = rtR3InitArgv(fFlags, cArgs, papszArgs);
580 return rc;
581 }
582 ASMAtomicWriteBool(&g_fInitializing, true);
583
584 /*
585 * Do the initialization.
586 */
587 int rc = rtR3InitBody(fFlags, cArgs, papszArgs, pszProgramPath);
588 if (RT_FAILURE(rc))
589 {
590 /* failure */
591 ASMAtomicWriteBool(&g_fInitializing, false);
592 ASMAtomicDecS32(&g_cUsers);
593 return rc;
594 }
595
596 /* success */
597 LogFlow(("rtR3Init: returns VINF_SUCCESS\n"));
598 ASMAtomicWriteBool(&g_fInitializing, false);
599 return VINF_SUCCESS;
600}
601
602
603RTR3DECL(int) RTR3InitExe(int cArgs, char ***papszArgs, uint32_t fFlags)
604{
605 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
606 return rtR3Init(fFlags, cArgs, papszArgs, NULL);
607}
608
609
610RTR3DECL(int) RTR3InitExeNoArguments(uint32_t fFlags)
611{
612 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
613 return rtR3Init(fFlags, 0, NULL, NULL);
614}
615
616
617RTR3DECL(int) RTR3InitDll(uint32_t fFlags)
618{
619 Assert(!(fFlags & RTR3INIT_FLAGS_DLL));
620 return rtR3Init(fFlags | RTR3INIT_FLAGS_DLL, 0, NULL, NULL);
621}
622
623
624RTR3DECL(int) RTR3InitEx(uint32_t iVersion, uint32_t fFlags, int cArgs, char ***papszArgs, const char *pszProgramPath)
625{
626 AssertReturn(iVersion == RTR3INIT_VER_CUR, VERR_NOT_SUPPORTED);
627 return rtR3Init(fFlags, cArgs, papszArgs, pszProgramPath);
628}
629
630RTR3DECL(bool) RTR3InitIsUnobtrusive(void)
631{
632 return RT_BOOL(g_fInitFlags & RTR3INIT_FLAGS_UNOBTRUSIVE);
633}
634
635#if 0 /** @todo implement RTR3Term. */
636RTR3DECL(void) RTR3Term(void)
637{
638}
639#endif
640
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