OSDN Git Service

errno and *_init cleanup
[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 #include <unistd.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <elf.h>
22 #include <link.h>
23 #include <bits/uClibc_page.h>
24 #include <paths.h>
25 #include <errno.h>
26 #include <netdb.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/sysmacros.h>
31 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
32 #include <pthread-functions.h>
33 #include <not-cancel.h>
34 #include <atomic.h>
35 #endif
36 #ifdef __UCLIBC_HAS_THREADS__
37 #include <pthread.h>
38 #endif 
39 #ifdef __UCLIBC_HAS_LOCALE__
40 #include <locale.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 #ifdef __UCLIBC_HAS_THREADS__
120 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
121 extern void weak_function __pthread_initialize_minimal(void);
122 #else
123 extern void __pthread_initialize_minimal(void);
124 #endif
125 #endif
126
127 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation and finalisation
128  * is handled by the routines passed to __uClibc_main().  */
129 #if defined (__UCLIBC_CTOR_DTOR__) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
130 extern void _dl_app_init_array(void);
131 extern void _dl_app_fini_array(void);
132 # ifndef SHARED
133 /* These magic symbols are provided by the linker.  */
134 extern void (*__preinit_array_start []) (void) attribute_hidden;
135 extern void (*__preinit_array_end []) (void) attribute_hidden;
136 extern void (*__init_array_start []) (void) attribute_hidden;
137 extern void (*__init_array_end []) (void) attribute_hidden;
138 extern void (*__fini_array_start []) (void) attribute_hidden;
139 extern void (*__fini_array_end []) (void) attribute_hidden;
140 # endif
141 #endif
142
143 attribute_hidden const char *__uclibc_progname = "";
144 #ifdef __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
145 const char *program_invocation_short_name = "";
146 const char *program_invocation_name = "";
147 #endif
148 #ifdef __UCLIBC_HAS___PROGNAME__
149 weak_alias (program_invocation_short_name, __progname)
150 weak_alias (program_invocation_name, __progname_full)
151 #endif
152
153 /*
154  * Declare the __environ global variable and create a weak alias environ.
155  * This must be initialized; we cannot have a weak alias into bss.
156  */
157 char **__environ = 0;
158 weak_alias(__environ, environ)
159
160 /* TODO: don't export __pagesize; we cant now because libpthread uses it */
161 size_t __pagesize = 0;
162
163 #ifndef O_NOFOLLOW
164 # define O_NOFOLLOW     0
165 #endif
166
167 #ifndef __ARCH_HAS_NO_LDSO__
168 static void __check_one_fd(int fd, int mode)
169 {
170     /* Check if the specified fd is already open */
171     if (fcntl(fd, F_GETFD) == -1)
172     {
173         /* The descriptor is probably not open, so try to use /dev/null */
174         int nullfd = open(_PATH_DEVNULL, mode);
175         /* /dev/null is major=1 minor=3.  Make absolutely certain
176          * that is in fact the device that we have opened and not
177          * some other wierd file... [removed in uclibc] */
178         if (nullfd!=fd)
179         {
180                 abort();
181         }
182     }
183 }
184
185 static int __check_suid(void)
186 {
187     uid_t uid, euid;
188     gid_t gid, egid;
189
190     uid  = getuid();
191     euid = geteuid();
192     if (uid != euid)
193         return 1;
194     gid  = getgid();
195     egid = getegid();
196     if (gid != egid)
197         return 1;
198     return 0; /* we are not suid */
199 }
200 #endif
201
202 /* __uClibc_init completely initialize uClibc so it is ready to use.
203  *
204  * On ELF systems (with a dynamic loader) this function must be called
205  * from the dynamic loader (see TIS and ELF Specification), so that
206  * constructors of shared libraries (which depend on libc) can use all
207  * the libc code without restriction.  For this we link the shared
208  * version of the uClibc with -init __uClibc_init so DT_INIT for
209  * uClibc is the address of __uClibc_init
210  *
211  * In all other cases we call it from the main stub
212  * __uClibc_main.
213  */
214
215 extern void __uClibc_init(void) attribute_hidden;
216 void __uClibc_init(void)
217 {
218     /* Don't recurse */
219     if (__pagesize)
220         return;
221
222     /* Setup an initial value.  This may not be perfect, but is
223      * better than  malloc using __pagesize=0 for atexit, ctors, etc.  */
224     __pagesize = PAGE_SIZE;
225
226 #ifdef __UCLIBC_HAS_THREADS__
227     /* Before we start initializing uClibc we have to call
228      * __pthread_initialize_minimal so we can use pthread_locks
229      * whenever they are needed.
230      */
231 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
232     if (likely(__pthread_initialize_minimal!=NULL))
233 #endif
234         __pthread_initialize_minimal();
235 #endif
236
237 #ifndef SHARED
238 # ifdef __UCLIBC_HAS_SSP__
239     /* Set up the stack checker's canary.  */
240     stack_chk_guard = _dl_setup_stack_chk_guard();
241 #  ifdef THREAD_SET_STACK_GUARD
242     THREAD_SET_STACK_GUARD (stack_chk_guard);
243 #  else
244     __stack_chk_guard = stack_chk_guard;
245 #  endif
246 #  ifdef __UCLIBC_HAS_SSP_COMPAT__
247     __guard = stack_chk_guard;
248 #  endif
249 # endif
250 #endif
251
252 #ifdef __UCLIBC_HAS_LOCALE__
253     /* Initialize the global locale structure. */
254     if (likely(not_null_ptr(_locale_init)))
255         _locale_init();
256 #endif
257
258     /*
259      * Initialize stdio here.  In the static library case, this will
260      * be bypassed if not needed because of the weak alias above.
261      * Thus we get a nice size savings because the stdio functions
262      * won't be pulled into the final static binary unless used.
263      */
264     if (likely(not_null_ptr(_stdio_init)))
265         _stdio_init();
266
267 }
268
269 #ifdef __UCLIBC_CTOR_DTOR__
270 void attribute_hidden (*__app_fini)(void) = NULL;
271 #endif
272
273 void attribute_hidden (*__rtld_fini)(void) = NULL;
274
275 extern void __uClibc_fini(void) attribute_hidden;
276 void __uClibc_fini(void)
277 {
278 #ifdef __UCLIBC_CTOR_DTOR__
279     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array finalisation is handled
280      * by __app_fini.  */
281 # ifdef SHARED
282     _dl_app_fini_array();
283 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
284     size_t i = __fini_array_end - __fini_array_start;
285     while (i-- > 0)
286         (*__fini_array_start [i]) ();
287 # endif
288     if (__app_fini != NULL)
289         (__app_fini)();
290 #endif
291     if (__rtld_fini != NULL)
292         (__rtld_fini)();
293 }
294
295 #ifndef SHARED
296 extern void __nptl_deallocate_tsd (void) __attribute ((weak));
297 extern unsigned int __nptl_nthreads __attribute ((weak));
298 #endif
299
300 /* __uClibc_main is the new main stub for uClibc. This function is
301  * called from crt1 (version 0.9.28 or newer), after ALL shared libraries
302  * are initialized, just before we call the application's main function.
303  */
304 void __uClibc_main(int (*main)(int, char **, char **), int argc,
305                     char **argv, void (*app_init)(void), void (*app_fini)(void),
306                     void (*rtld_fini)(void),
307                     void *stack_end attribute_unused) attribute_noreturn;
308 void __uClibc_main(int (*main)(int, char **, char **), int argc,
309                     char **argv, void (*app_init)(void), void (*app_fini)(void),
310                     void (*rtld_fini)(void), void *stack_end attribute_unused)
311 {
312 #ifndef __ARCH_HAS_NO_LDSO__
313     unsigned long *aux_dat;
314     ElfW(auxv_t) auxvt[AT_EGID + 1];
315 #endif
316
317 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
318         /* Result of the 'main' function.  */
319         int result;
320 #endif
321
322 #ifndef SHARED
323     __libc_stack_end = stack_end;
324 #endif
325
326     __rtld_fini = rtld_fini;
327
328     /* The environment begins right after argv.  */
329     __environ = &argv[argc + 1];
330
331     /* If the first thing after argv is the arguments
332      * then the environment is empty. */
333     if ((char *) __environ == *argv) {
334         /* Make __environ point to the NULL at argv[argc] */
335         __environ = &argv[argc];
336     }
337
338 #ifndef __ARCH_HAS_NO_LDSO__
339     /* Pull stuff from the ELF header when possible */
340     memset(auxvt, 0x00, sizeof(auxvt));
341     aux_dat = (unsigned long*)__environ;
342     while (*aux_dat) {
343         aux_dat++;
344     }
345     aux_dat++;
346     while (*aux_dat) {
347         ElfW(auxv_t) *auxv_entry = (ElfW(auxv_t) *) aux_dat;
348         if (auxv_entry->a_type <= AT_EGID) {
349             memcpy(&(auxvt[auxv_entry->a_type]), auxv_entry, sizeof(ElfW(auxv_t)));
350         }
351         aux_dat += 2;
352     }
353 #ifndef SHARED
354     /* Get the program headers (_dl_phdr) from the aux vector
355        It will be used into __libc_setup_tls. */
356
357     _dl_aux_init (auxvt);
358 #endif
359 #endif
360
361     /* We need to initialize uClibc.  If we are dynamically linked this
362      * may have already been completed by the shared lib loader.  We call
363      * __uClibc_init() regardless, to be sure the right thing happens. */
364     __uClibc_init();
365
366 #ifndef __ARCH_HAS_NO_LDSO__
367     /* Make certain getpagesize() gives the correct answer */
368     __pagesize = (auxvt[AT_PAGESZ].a_un.a_val)? auxvt[AT_PAGESZ].a_un.a_val : PAGE_SIZE;
369
370     /* Prevent starting SUID binaries where the stdin. stdout, and
371      * stderr file descriptors are not already opened. */
372     if ((auxvt[AT_UID].a_un.a_val == (size_t)-1 && __check_suid()) ||
373             (auxvt[AT_UID].a_un.a_val != (size_t)-1 &&
374             (auxvt[AT_UID].a_un.a_val != auxvt[AT_EUID].a_un.a_val ||
375              auxvt[AT_GID].a_un.a_val != auxvt[AT_EGID].a_un.a_val)))
376     {
377         __check_one_fd (STDIN_FILENO, O_RDONLY | O_NOFOLLOW);
378         __check_one_fd (STDOUT_FILENO, O_RDWR | O_NOFOLLOW);
379         __check_one_fd (STDERR_FILENO, O_RDWR | O_NOFOLLOW);
380     }
381 #endif
382
383     __uclibc_progname = *argv;
384 #ifdef __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
385     if (*argv != NULL) {
386         program_invocation_name = *argv;
387         program_invocation_short_name = strrchr(*argv, '/');
388         if (program_invocation_short_name != NULL)
389             ++program_invocation_short_name;
390         else
391             program_invocation_short_name = program_invocation_name;
392     }
393 #endif
394
395 #ifdef __UCLIBC_CTOR_DTOR__
396     /* Arrange for the application's dtors to run before we exit.  */
397     __app_fini = app_fini;
398
399     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
400      * by __app_init.  */
401 # if !defined (SHARED) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
402     /* For dynamically linked executables the preinit array is executed by
403        the dynamic linker (before initializing any shared object).
404        For static executables, preinit happens rights before init.  */
405     {
406         const size_t size = __preinit_array_end - __preinit_array_start;
407         size_t i;
408         for (i = 0; i < size; i++)
409             (*__preinit_array_start [i]) ();
410     }
411 # endif
412     /* Run all the application's ctors now.  */
413     if (app_init!=NULL) {
414         app_init();
415     }
416     /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
417      * by __app_init.  */
418 # ifdef SHARED
419     _dl_app_init_array();
420 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
421     {
422         const size_t size = __init_array_end - __init_array_start;
423         size_t i;
424         for (i = 0; i < size; i++)
425             (*__init_array_start [i]) ();
426     }
427 # endif
428 #endif
429
430     /* Note: It is possible that any initialization done above could
431      * have resulted in errno being set nonzero, so set it to 0 before
432      * we call main.
433      */
434     if (likely(not_null_ptr(__errno_location)))
435         *(__errno_location()) = 0;
436
437     /* Set h_errno to 0 as well */
438     if (likely(not_null_ptr(__h_errno_location)))
439         *(__h_errno_location()) = 0;
440
441 #if defined HAVE_CLEANUP_JMP_BUF && defined __UCLIBC_HAS_THREADS_NATIVE__
442         /* Memory for the cancellation buffer.  */
443         struct pthread_unwind_buf unwind_buf;
444
445         int not_first_call;
446         not_first_call =
447                 setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
448         if (__builtin_expect (! not_first_call, 1))
449         {
450                 struct pthread *self = THREAD_SELF;
451
452                 /* Store old info.  */
453                 unwind_buf.priv.data.prev = THREAD_GETMEM (self, cleanup_jmp_buf);
454                 unwind_buf.priv.data.cleanup = THREAD_GETMEM (self, cleanup);
455
456                 /* Store the new cleanup handler info.  */
457                 THREAD_SETMEM (self, cleanup_jmp_buf, &unwind_buf);
458
459                 /* Run the program.  */
460                 result = main (argc, argv, __environ);
461         }
462         else
463         {
464                 /* Remove the thread-local data.  */
465 # ifdef SHARED
466                 __libc_pthread_functions.ptr__nptl_deallocate_tsd ();
467 # else
468                 __nptl_deallocate_tsd ();
469 # endif
470
471                 /* One less thread.  Decrement the counter.  If it is zero we
472                    terminate the entire process.  */
473                 result = 0;
474 # ifdef SHARED
475                 unsigned int *const ptr = __libc_pthread_functions.ptr_nthreads;
476 # else
477                 unsigned int *const ptr = &__nptl_nthreads;
478 # endif
479
480                 if (! atomic_decrement_and_test (ptr))
481                         /* Not much left to do but to exit the thread, not the process.  */
482                         __exit_thread_inline (0);
483         }
484
485         exit (result);
486 #else
487         /*
488          * Finally, invoke application's main and then exit.
489          */
490         exit (main (argc, argv, __environ));
491 #endif
492 }