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