OSDN Git Service

librt: provide missing prototypes for mq_timedreceive,mq_timedsend
[uclinux-h8/uClibc.git] / libc / misc / internals / __uClibc_main.c
1 /*
2  * Copyright (C) 2006 by Steven J. Hill <sjhill@realitydiluted.com>
3  * Copyright (C) 2001 by Manuel Novoa III <mjn3@uclibc.org>
4  * Copyright (C) 2000-2005 Erik Andersen <andersen@uclibc.org>
5  *
6  * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
7  *
8  * __uClibc_main is the routine to be called by all the arch-specific
9  * versions of crt1.S in uClibc.
10  *
11  * It is meant to handle any special initialization needed by the library
12  * such as setting the global variable(s) __environ (environ) and
13  * initializing the stdio package.  Using weak symbols, the latter is
14  * avoided in the static library case.
15  */
16
17 #include <features.h>
18 #ifndef __UCLIBC_HAS_THREADS_NATIVE__
19 #define _ERRNO_H
20 #endif
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <elf.h>
25 #include <link.h>
26 #include <bits/uClibc_page.h>
27 #include <paths.h>
28 #include <unistd.h>
29 #include <asm/errno.h>
30 #include <fcntl.h>
31 #include <sys/stat.h>
32 #include <sys/sysmacros.h>
33 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
34 #include <errno.h>
35 #include <pthread-functions.h>
36 #include <not-cancel.h>
37 #include <atomic.h>
38 #endif
39 #ifdef __UCLIBC_HAS_THREADS__
40 #include <pthread.h>
41 #endif 
42
43 #ifndef SHARED
44 void *__libc_stack_end = NULL;
45
46 # ifdef __UCLIBC_HAS_SSP__
47 #  include <dl-osinfo.h>
48 static uintptr_t stack_chk_guard;
49 #  ifndef THREAD_SET_STACK_GUARD
50 /* Only exported for architectures that don't store the stack guard canary
51  * in thread local area. */
52 /* for gcc-4.1 non-TLS */
53 uintptr_t __stack_chk_guard attribute_relro;
54 #  endif
55 /* for gcc-3.x + Etoh ssp */
56 #  ifdef __UCLIBC_HAS_SSP_COMPAT__
57 uintptr_t __guard attribute_relro;
58 #  endif
59 # endif
60
61 /*
62  * Needed to initialize _dl_phdr when statically linked
63  */
64
65 void internal_function _dl_aux_init (ElfW(auxv_t) *av);
66
67 #ifdef __UCLIBC_HAS_THREADS__
68 /*
69  * uClibc internal locking requires that we have weak aliases
70  * for dummy functions in case libpthread.a is not linked in.
71  * This needs to be in compilation unit that is pulled always
72  * in or linker will disregard these weaks.
73  */
74
75 static int __pthread_return_0 (pthread_mutex_t *unused) { return 0; }
76 weak_alias (__pthread_return_0, __pthread_mutex_lock)
77 weak_alias (__pthread_return_0, __pthread_mutex_trylock)
78 weak_alias (__pthread_return_0, __pthread_mutex_unlock)
79
80 int weak_function
81 __pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
82 {
83         return 0;
84 }
85
86 void weak_function
87 _pthread_cleanup_push_defer(struct _pthread_cleanup_buffer *__buffer,
88                             void (*__routine) (void *), void *__arg)
89 {
90         __buffer->__routine = __routine;
91         __buffer->__arg = __arg;
92 }
93
94 void weak_function
95 _pthread_cleanup_pop_restore(struct _pthread_cleanup_buffer *__buffer,
96                              int __execute)
97 {
98         if (__execute)
99                 __buffer->__routine(__buffer->__arg);
100 }
101 #endif /* __UCLIBC_HAS_THREADS__ */
102
103 #endif /* !SHARED */
104
105 /* Defeat compiler optimization which assumes function addresses are never NULL */
106 static __always_inline int not_null_ptr(const void *p)
107 {
108         const void *q;
109         __asm__ (""
110                 : "=r" (q) /* output */
111                 : "0" (p) /* input */
112         );
113         return q != 0;
114 }
115
116 /*
117  * Prototypes.
118  */
119 extern int *weak_const_function __errno_location(void);
120 extern int *weak_const_function __h_errno_location(void);
121 extern void weak_function _stdio_init(void) attribute_hidden;
122 #ifdef __UCLIBC_HAS_LOCALE__
123 extern void weak_function _locale_init(void) attribute_hidden;
124 #endif
125 #ifdef __UCLIBC_HAS_THREADS__
126 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
127 extern void weak_function __pthread_initialize_minimal(void);
128 #else
129 extern void __pthread_initialize_minimal(void);
130 #endif
131 #endif
132
133 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation and finalisation
134  * is handled by the routines passed to __uClibc_main().  */
135 #if defined (__UCLIBC_CTOR_DTOR__) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
136 extern void _dl_app_init_array(void);
137 extern void _dl_app_fini_array(void);
138 # ifndef SHARED
139 /* These magic symbols are provided by the linker.  */
140 extern void (*__preinit_array_start []) (void) attribute_hidden;
141 extern void (*__preinit_array_end []) (void) attribute_hidden;
142 extern void (*__init_array_start []) (void) attribute_hidden;
143 extern void (*__init_array_end []) (void) attribute_hidden;
144 extern void (*__fini_array_start []) (void) attribute_hidden;
145 extern void (*__fini_array_end []) (void) attribute_hidden;
146 # endif
147 #endif
148
149 attribute_hidden const char *__uclibc_progname = "";
150 #ifdef __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
151 const char *program_invocation_short_name = "";
152 const char *program_invocation_name = "";
153 #endif
154 #ifdef __UCLIBC_HAS___PROGNAME__
155 weak_alias (program_invocation_short_name, __progname)
156 weak_alias (program_invocation_name, __progname_full)
157 #endif
158
159 /*
160  * Declare the __environ global variable and create a weak alias environ.
161  * This must be initialized; we cannot have a weak alias into bss.
162  */
163 char **__environ = 0;
164 weak_alias(__environ, environ)
165
166 /* TODO: don't export __pagesize; we cant now because libpthread uses it */
167 size_t __pagesize = 0;
168
169 #ifndef O_NOFOLLOW
170 # define O_NOFOLLOW     0
171 #endif
172
173 #ifndef __ARCH_HAS_NO_LDSO__
174 static void __check_one_fd(int fd, int mode)
175 {
176     /* Check if the specified fd is already open */
177     if (fcntl(fd, F_GETFD) == -1)
178     {
179         /* The descriptor is probably not open, so try to use /dev/null */
180         int nullfd = open(_PATH_DEVNULL, mode);
181         /* /dev/null is major=1 minor=3.  Make absolutely certain
182          * that is in fact the device that we have opened and not
183          * some other wierd file... [removed in uclibc] */
184         if (nullfd!=fd)
185         {
186                 abort();
187         }
188     }
189 }
190
191 static int __check_suid(void)
192 {
193     uid_t uid, euid;
194     gid_t gid, egid;
195
196     uid  = getuid();
197     euid = geteuid();
198     if (uid != euid)
199         return 1;
200     gid  = getgid();
201     egid = getegid();
202     if (gid != egid)
203         return 1;
204     return 0; /* we are not suid */
205 }
206 #endif
207
208 /* __uClibc_init completely initialize uClibc so it is ready to use.
209  *
210  * On ELF systems (with a dynamic loader) this function must be called
211  * from the dynamic loader (see TIS and ELF Specification), so that
212  * constructors of shared libraries (which depend on libc) can use all
213  * the libc code without restriction.  For this we link the shared
214  * version of the uClibc with -init __uClibc_init so DT_INIT for
215  * uClibc is the address of __uClibc_init
216  *
217  * In all other cases we call it from the main stub
218  * __uClibc_main.
219  */
220
221 extern void __uClibc_init(void) attribute_hidden;
222 void __uClibc_init(void)
223 {
224     /* Don't recurse */
225     if (__pagesize)
226         return;
227
228     /* Setup an initial value.  This may not be perfect, but is
229      * better than  malloc using __pagesize=0 for atexit, ctors, etc.  */
230     __pagesize = PAGE_SIZE;
231
232 #ifdef __UCLIBC_HAS_THREADS__
233     /* Before we start initializing uClibc we have to call
234      * __pthread_initialize_minimal so we can use pthread_locks
235      * whenever they are needed.
236      */
237 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
238     if (likely(__pthread_initialize_minimal!=NULL))
239 #endif
240         __pthread_initialize_minimal();
241 #endif
242
243 #ifndef SHARED
244 # ifdef __UCLIBC_HAS_SSP__
245     /* Set up the stack checker's canary.  */
246     stack_chk_guard = _dl_setup_stack_chk_guard();
247 #  ifdef THREAD_SET_STACK_GUARD
248     THREAD_SET_STACK_GUARD (stack_chk_guard);
249 #  else
250     __stack_chk_guard = stack_chk_guard;
251 #  endif
252 #  ifdef __UCLIBC_HAS_SSP_COMPAT__
253     __guard = stack_chk_guard;
254 #  endif
255 # endif
256 #endif
257
258 #ifdef __UCLIBC_HAS_LOCALE__
259     /* Initialize the global locale structure. */
260     if (likely(not_null_ptr(_locale_init)))
261         _locale_init();
262 #endif
263
264     /*
265      * Initialize stdio here.  In the static library case, this will
266      * be bypassed if not needed because of the weak alias above.
267      * Thus we get a nice size savings because the stdio functions
268      * won't be pulled into the final static binary unless used.
269      */
270     if (likely(not_null_ptr(_stdio_init)))
271         _stdio_init();
272
273 }
274
275 #ifdef __UCLIBC_CTOR_DTOR__
276 void attribute_hidden (*__app_fini)(void) = NULL;
277 #endif
278
279 void attribute_hidden (*__rtld_fini)(void) = NULL;
280
281 extern void __uClibc_fini(void) attribute_hidden;
282 void __uClibc_fini(void)
283 {
284 #ifdef __UCLIBC_CTOR_DTOR__
285     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array finalisation is handled
286      * by __app_fini.  */
287 # ifdef SHARED
288     _dl_app_fini_array();
289 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
290     size_t i = __fini_array_end - __fini_array_start;
291     while (i-- > 0)
292         (*__fini_array_start [i]) ();
293 # endif
294     if (__app_fini != NULL)
295         (__app_fini)();
296 #endif
297     if (__rtld_fini != NULL)
298         (__rtld_fini)();
299 }
300
301 #ifndef SHARED
302 extern void __nptl_deallocate_tsd (void) __attribute ((weak));
303 extern unsigned int __nptl_nthreads __attribute ((weak));
304 #endif
305
306 /* __uClibc_main is the new main stub for uClibc. This function is
307  * called from crt1 (version 0.9.28 or newer), after ALL shared libraries
308  * are initialized, just before we call the application's main function.
309  */
310 void __uClibc_main(int (*main)(int, char **, char **), int argc,
311                     char **argv, void (*app_init)(void), void (*app_fini)(void),
312                     void (*rtld_fini)(void),
313                     void *stack_end attribute_unused) attribute_noreturn;
314 void __uClibc_main(int (*main)(int, char **, char **), int argc,
315                     char **argv, void (*app_init)(void), void (*app_fini)(void),
316                     void (*rtld_fini)(void), void *stack_end attribute_unused)
317 {
318 #ifndef __ARCH_HAS_NO_LDSO__
319     unsigned long *aux_dat;
320     ElfW(auxv_t) auxvt[AT_EGID + 1];
321 #endif
322
323 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
324         /* Result of the 'main' function.  */
325         int result;
326 #endif
327
328 #ifndef SHARED
329     __libc_stack_end = stack_end;
330 #endif
331
332     __rtld_fini = rtld_fini;
333
334     /* The environment begins right after argv.  */
335     __environ = &argv[argc + 1];
336
337     /* If the first thing after argv is the arguments
338      * then the environment is empty. */
339     if ((char *) __environ == *argv) {
340         /* Make __environ point to the NULL at argv[argc] */
341         __environ = &argv[argc];
342     }
343
344 #ifndef __ARCH_HAS_NO_LDSO__
345     /* Pull stuff from the ELF header when possible */
346     memset(auxvt, 0x00, sizeof(auxvt));
347     aux_dat = (unsigned long*)__environ;
348     while (*aux_dat) {
349         aux_dat++;
350     }
351     aux_dat++;
352     while (*aux_dat) {
353         ElfW(auxv_t) *auxv_entry = (ElfW(auxv_t) *) aux_dat;
354         if (auxv_entry->a_type <= AT_EGID) {
355             memcpy(&(auxvt[auxv_entry->a_type]), auxv_entry, sizeof(ElfW(auxv_t)));
356         }
357         aux_dat += 2;
358     }
359 #ifndef SHARED
360     /* Get the program headers (_dl_phdr) from the aux vector
361        It will be used into __libc_setup_tls. */
362
363     _dl_aux_init (auxvt);
364 #endif
365 #endif
366
367     /* We need to initialize uClibc.  If we are dynamically linked this
368      * may have already been completed by the shared lib loader.  We call
369      * __uClibc_init() regardless, to be sure the right thing happens. */
370     __uClibc_init();
371
372 #ifndef __ARCH_HAS_NO_LDSO__
373     /* Make certain getpagesize() gives the correct answer */
374     __pagesize = (auxvt[AT_PAGESZ].a_un.a_val)? auxvt[AT_PAGESZ].a_un.a_val : PAGE_SIZE;
375
376     /* Prevent starting SUID binaries where the stdin. stdout, and
377      * stderr file descriptors are not already opened. */
378     if ((auxvt[AT_UID].a_un.a_val == (size_t)-1 && __check_suid()) ||
379             (auxvt[AT_UID].a_un.a_val != (size_t)-1 &&
380             (auxvt[AT_UID].a_un.a_val != auxvt[AT_EUID].a_un.a_val ||
381              auxvt[AT_GID].a_un.a_val != auxvt[AT_EGID].a_un.a_val)))
382     {
383         __check_one_fd (STDIN_FILENO, O_RDONLY | O_NOFOLLOW);
384         __check_one_fd (STDOUT_FILENO, O_RDWR | O_NOFOLLOW);
385         __check_one_fd (STDERR_FILENO, O_RDWR | O_NOFOLLOW);
386     }
387 #endif
388
389     __uclibc_progname = *argv;
390 #ifdef __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
391     if (*argv != NULL) {
392         program_invocation_name = *argv;
393         program_invocation_short_name = strrchr(*argv, '/');
394         if (program_invocation_short_name != NULL)
395             ++program_invocation_short_name;
396         else
397             program_invocation_short_name = program_invocation_name;
398     }
399 #endif
400
401 #ifdef __UCLIBC_CTOR_DTOR__
402     /* Arrange for the application's dtors to run before we exit.  */
403     __app_fini = app_fini;
404
405     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
406      * by __app_init.  */
407 # if !defined (SHARED) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
408     /* For dynamically linked executables the preinit array is executed by
409        the dynamic linker (before initializing any shared object).
410        For static executables, preinit happens rights before init.  */
411     {
412         const size_t size = __preinit_array_end - __preinit_array_start;
413         size_t i;
414         for (i = 0; i < size; i++)
415             (*__preinit_array_start [i]) ();
416     }
417 # endif
418     /* Run all the application's ctors now.  */
419     if (app_init!=NULL) {
420         app_init();
421     }
422     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
423      * by __app_init.  */
424 # ifdef SHARED
425     _dl_app_init_array();
426 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
427     {
428         const size_t size = __init_array_end - __init_array_start;
429         size_t i;
430         for (i = 0; i < size; i++)
431             (*__init_array_start [i]) ();
432     }
433 # endif
434 #endif
435
436     /* Note: It is possible that any initialization done above could
437      * have resulted in errno being set nonzero, so set it to 0 before
438      * we call main.
439      */
440     if (likely(not_null_ptr(__errno_location)))
441         *(__errno_location()) = 0;
442
443     /* Set h_errno to 0 as well */
444     if (likely(not_null_ptr(__h_errno_location)))
445         *(__h_errno_location()) = 0;
446
447 #if defined HAVE_CLEANUP_JMP_BUF && defined __UCLIBC_HAS_THREADS_NATIVE__
448         /* Memory for the cancellation buffer.  */
449         struct pthread_unwind_buf unwind_buf;
450
451         int not_first_call;
452         not_first_call =
453                 setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
454         if (__builtin_expect (! not_first_call, 1))
455         {
456                 struct pthread *self = THREAD_SELF;
457
458                 /* Store old info.  */
459                 unwind_buf.priv.data.prev = THREAD_GETMEM (self, cleanup_jmp_buf);
460                 unwind_buf.priv.data.cleanup = THREAD_GETMEM (self, cleanup);
461
462                 /* Store the new cleanup handler info.  */
463                 THREAD_SETMEM (self, cleanup_jmp_buf, &unwind_buf);
464
465                 /* Run the program.  */
466                 result = main (argc, argv, __environ);
467         }
468         else
469         {
470                 /* Remove the thread-local data.  */
471 # ifdef SHARED
472                 __libc_pthread_functions.ptr__nptl_deallocate_tsd ();
473 # else
474                 __nptl_deallocate_tsd ();
475 # endif
476
477                 /* One less thread.  Decrement the counter.  If it is zero we
478                    terminate the entire process.  */
479                 result = 0;
480 # ifdef SHARED
481                 unsigned int *const ptr = __libc_pthread_functions.ptr_nthreads;
482 # else
483                 unsigned int *const ptr = &__nptl_nthreads;
484 # endif
485
486                 if (! atomic_decrement_and_test (ptr))
487                         /* Not much left to do but to exit the thread, not the process.  */
488                         __exit_thread_inline (0);
489         }
490
491         exit (result);
492 #else
493         /*
494          * Finally, invoke application's main and then exit.
495          */
496         exit (main (argc, argv, __environ));
497 #endif
498 }