threads: optimize single threaded applications
[uclibc-ng.git] / libc / misc / internals / __uClibc_main.c
blobd80565e2c20fbd69b27eb7c5edd26f554f610d70
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>
6 * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
8 * __uClibc_main is the routine to be called by all the arch-specific
9 * versions of crt1.S in uClibc.
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.
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 #ifndef __ARCH_HAS_NO_LDSO__
29 #include <fcntl.h>
30 #endif
31 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
32 #include <not-cancel.h>
33 #include <atomic.h>
34 #include <tls.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
43 /* Are we in a secure process environment or are we dealing
44 * with setuid stuff? If we are dynamically linked, then we
45 * already have _dl_secure, otherwise we need to re-examine
46 * auxvt[] below.
48 int _pe_secure = 0;
49 libc_hidden_data_def(_pe_secure)
51 #ifndef SHARED
52 void *__libc_stack_end = NULL;
54 # ifdef __UCLIBC_HAS_SSP__
55 # include <dl-osinfo.h>
56 static uintptr_t stack_chk_guard;
57 # ifndef THREAD_SET_STACK_GUARD
58 /* Only exported for architectures that don't store the stack guard canary
59 * in thread local area. */
60 /* for gcc-4.1 non-TLS */
61 uintptr_t __stack_chk_guard attribute_relro;
62 # endif
63 # endif
66 * Needed to initialize _dl_phdr when statically linked
69 void internal_function _dl_aux_init (ElfW(auxv_t) *av);
71 #ifdef __UCLIBC_HAS_THREADS__
73 * uClibc internal locking requires that we have weak aliases
74 * for dummy functions in case a single threaded application is linked.
75 * This needs to be in compilation unit that is pulled always
76 * in or linker will disregard these weaks.
79 static int __pthread_return_0 (pthread_mutex_t *unused) { return 0; }
80 weak_alias (__pthread_return_0, __pthread_mutex_lock)
81 weak_alias (__pthread_return_0, __pthread_mutex_trylock)
82 weak_alias (__pthread_return_0, __pthread_mutex_unlock)
84 int weak_function
85 __pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
87 return 0;
90 void weak_function
91 _pthread_cleanup_push_defer(struct _pthread_cleanup_buffer *__buffer,
92 void (*__routine) (void *), void *__arg)
94 __buffer->__routine = __routine;
95 __buffer->__arg = __arg;
98 void weak_function
99 _pthread_cleanup_pop_restore(struct _pthread_cleanup_buffer *__buffer,
100 int __execute)
102 if (__execute)
103 __buffer->__routine(__buffer->__arg);
106 #endif /* __UCLIBC_HAS_THREADS__ */
108 #endif /* !SHARED */
110 /* Defeat compiler optimization which assumes function addresses are never NULL */
111 static __always_inline int not_null_ptr(const void *p)
113 const void *q;
114 __asm__ (""
115 : "=r" (q) /* output */
116 : "0" (p) /* input */
118 return q != 0;
122 * Prototypes.
124 #ifdef __UCLIBC_HAS_THREADS__
125 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
126 extern void weak_function __pthread_initialize_minimal(void);
127 #else
128 extern void __pthread_initialize_minimal(void);
129 #endif
130 #endif
132 #ifndef SHARED
133 extern void __libc_setup_tls (size_t tcbsize, size_t tcbalign);
134 #endif
136 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation and finalisation
137 * is handled by the routines passed to __uClibc_main(). */
138 #if defined (__UCLIBC_CTOR_DTOR__) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
139 extern void _dl_app_init_array(void);
140 extern void _dl_app_fini_array(void);
141 # ifndef SHARED
142 /* These magic symbols are provided by the linker. */
143 extern void (*__preinit_array_start []) (void) attribute_hidden;
144 extern void (*__preinit_array_end []) (void) attribute_hidden;
145 extern void (*__init_array_start []) (void) attribute_hidden;
146 extern void (*__init_array_end []) (void) attribute_hidden;
147 extern void (*__fini_array_start []) (void) attribute_hidden;
148 extern void (*__fini_array_end []) (void) attribute_hidden;
149 # endif
150 #endif
152 #ifdef SHARED
153 extern int _dl_secure;
154 #endif
155 extern size_t _dl_pagesize;
157 const char *__uclibc_progname = "";
158 #if !defined __UCLIBC_HAS___PROGNAME__ && defined __USE_GNU && defined __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
159 # define __progname program_invocation_short_name
160 # define __progname_full program_invocation_name
161 #endif
162 #if defined __UCLIBC_HAS___PROGNAME__ || (defined __USE_GNU && defined __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__)
163 const char *__progname = "";
164 /* psm: why have a visible __progname_full? */
165 const char *__progname_full = "";
166 # if defined __UCLIBC_HAS___PROGNAME__ && defined __USE_GNU && defined __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__
167 weak_alias (__progname, program_invocation_short_name)
168 weak_alias (__progname_full, program_invocation_name)
169 # endif
170 #endif
173 * Declare the __environ global variable and create a weak alias environ.
174 * This must be initialized; we cannot have a weak alias into bss.
176 char **__environ = 0;
177 weak_alias(__environ, environ)
179 size_t __pagesize = 0;
181 #ifndef O_NOFOLLOW
182 # define O_NOFOLLOW 0
183 #endif
185 #ifndef __ARCH_HAS_NO_LDSO__
186 static void __check_one_fd(int fd, int mode)
188 /* Check if the specified fd is already open */
189 if (fcntl(fd, F_GETFD) == -1)
191 /* The descriptor is probably not open, so try to use /dev/null */
192 int nullfd = open(_PATH_DEVNULL, mode);
193 /* /dev/null is major=1 minor=3. Make absolutely certain
194 * that is in fact the device that we have opened and not
195 * some other wierd file... [removed in uclibc] */
196 if (nullfd!=fd)
198 abort();
203 #ifndef SHARED
204 static int __check_suid(void)
206 uid_t uid, euid;
207 gid_t gid, egid;
209 uid = getuid();
210 euid = geteuid();
211 if (uid != euid)
212 return 1;
213 gid = getgid();
214 egid = getegid();
215 if (gid != egid)
216 return 1;
217 return 0; /* we are not suid */
219 #endif
220 #endif
222 /* __uClibc_init completely initialize uClibc so it is ready to use.
224 * On ELF systems (with a dynamic loader) this function must be called
225 * from the dynamic loader (see TIS and ELF Specification), so that
226 * constructors of shared libraries (which depend on libc) can use all
227 * the libc code without restriction. For this we link the shared
228 * version of the uClibc with -init __uClibc_init so DT_INIT for
229 * uClibc is the address of __uClibc_init
231 * In all other cases we call it from the main stub
232 * __uClibc_main.
235 extern void __uClibc_init(void) attribute_hidden;
236 void __uClibc_init(void)
238 /* Don't recurse */
239 if (__pagesize)
240 return;
242 /* Setup an initial value. This may not be perfect, but is
243 * better than malloc using __pagesize=0 for atexit, ctors, etc. */
244 __pagesize = PAGE_SIZE;
246 #ifdef __UCLIBC_HAS_THREADS__
248 #if defined (__UCLIBC_HAS_THREADS_NATIVE__) && !defined (SHARED)
249 /* Unlike in the dynamically linked case the dynamic linker has not
250 taken care of initializing the TLS data structures. */
251 __libc_setup_tls (TLS_TCB_SIZE, TLS_TCB_ALIGN);
252 #endif
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.
258 #if !defined (__UCLIBC_HAS_THREADS_NATIVE__) || defined (SHARED)
259 if (likely(__pthread_initialize_minimal!=NULL))
260 #endif
261 __pthread_initialize_minimal();
262 #endif
264 #ifndef SHARED
265 # ifdef __UCLIBC_HAS_SSP__
266 /* Set up the stack checker's canary. */
267 stack_chk_guard = _dl_setup_stack_chk_guard();
268 # ifdef THREAD_SET_STACK_GUARD
269 THREAD_SET_STACK_GUARD (stack_chk_guard);
270 # else
271 __stack_chk_guard = stack_chk_guard;
272 # endif
273 # endif
274 #endif
276 #ifdef __UCLIBC_HAS_LOCALE__
277 /* Initialize the global locale structure. */
278 if (likely(not_null_ptr(_locale_init)))
279 _locale_init();
280 #endif
283 * Initialize stdio here. In the static library case, this will
284 * be bypassed if not needed because of the weak alias above.
285 * Thus we get a nice size savings because the stdio functions
286 * won't be pulled into the final static binary unless used.
288 if (likely(not_null_ptr(_stdio_init)))
289 _stdio_init();
293 #ifdef __UCLIBC_CTOR_DTOR__
294 void attribute_hidden (*__app_fini)(void) = NULL;
295 #endif
297 void attribute_hidden (*__rtld_fini)(void) = NULL;
299 extern void __uClibc_fini(void) attribute_hidden;
300 void __uClibc_fini(void)
302 #ifdef __UCLIBC_CTOR_DTOR__
303 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array finalisation is handled
304 * by __app_fini. */
305 # ifdef SHARED
306 _dl_app_fini_array();
307 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
308 size_t i = __fini_array_end - __fini_array_start;
309 while (i-- > 0)
310 (*__fini_array_start [i]) ();
311 # endif
312 if (__app_fini != NULL)
313 (__app_fini)();
314 #endif
315 if (__rtld_fini != NULL)
316 (__rtld_fini)();
319 #ifndef SHARED
320 extern void __nptl_deallocate_tsd (void) __attribute ((weak));
321 extern unsigned int __nptl_nthreads __attribute ((weak));
322 #endif
324 /* __uClibc_main is the new main stub for uClibc. This function is
325 * called from crt1 (version 0.9.28 or newer), after ALL shared libraries
326 * are initialized, just before we call the application's main function.
328 void __uClibc_main(int (*main)(int, char **, char **), int argc,
329 char **argv, void (*app_init)(void), void (*app_fini)(void),
330 void (*rtld_fini)(void),
331 void *stack_end attribute_unused) attribute_noreturn;
332 void __uClibc_main(int (*main)(int, char **, char **), int argc,
333 char **argv, void (*app_init)(void), void (*app_fini)(void),
334 void (*rtld_fini)(void), void *stack_end attribute_unused)
336 #if !defined __ARCH_HAS_NO_LDSO__ && !defined SHARED
337 unsigned long *aux_dat;
338 ElfW(auxv_t) auxvt[AT_EGID + 1];
339 #endif
341 #ifdef __UCLIBC_HAS_THREADS_NATIVE__
342 /* Result of the 'main' function. */
343 int result;
344 #endif
346 #ifndef SHARED
347 __libc_stack_end = stack_end;
348 #endif
350 __rtld_fini = rtld_fini;
352 /* The environment begins right after argv. */
353 __environ = &argv[argc + 1];
355 /* If the first thing after argv is the arguments
356 * then the environment is empty. */
357 if ((char *) __environ == *argv) {
358 /* Make __environ point to the NULL at argv[argc] */
359 __environ = &argv[argc];
362 #if !defined __ARCH_HAS_NO_LDSO__ && !defined SHARED
363 /* Pull stuff from the ELF header when possible */
364 memset(auxvt, 0x00, sizeof(auxvt));
365 aux_dat = (unsigned long*)__environ;
366 while (*aux_dat) {
367 aux_dat++;
369 aux_dat++;
370 while (*aux_dat) {
371 ElfW(auxv_t) *auxv_entry = (ElfW(auxv_t) *) aux_dat;
372 if (auxv_entry->a_type <= AT_EGID) {
373 memcpy(&(auxvt[auxv_entry->a_type]), auxv_entry, sizeof(ElfW(auxv_t)));
375 aux_dat += 2;
377 /* Get the program headers (_dl_phdr) from the aux vector
378 It will be used into __libc_setup_tls. */
380 _dl_aux_init (auxvt);
381 #endif
383 /* We need to initialize uClibc. If we are dynamically linked this
384 * may have already been completed by the shared lib loader. We call
385 * __uClibc_init() regardless, to be sure the right thing happens. */
386 __uClibc_init();
388 #ifndef __ARCH_HAS_NO_LDSO__
389 /* Make certain getpagesize() gives the correct answer.
390 * _dl_pagesize is defined into ld.so if SHARED or into libc.a otherwise. */
391 __pagesize = _dl_pagesize;
393 #ifndef SHARED
394 /* Prevent starting SUID binaries where the stdin. stdout, and
395 * stderr file descriptors are not already opened. */
396 if ((auxvt[AT_UID].a_un.a_val == (size_t)-1 && __check_suid()) ||
397 (auxvt[AT_UID].a_un.a_val != (size_t)-1 &&
398 (auxvt[AT_UID].a_un.a_val != auxvt[AT_EUID].a_un.a_val ||
399 auxvt[AT_GID].a_un.a_val != auxvt[AT_EGID].a_un.a_val)))
400 #else
401 if (_dl_secure)
402 #endif
404 __check_one_fd (STDIN_FILENO, O_RDONLY | O_NOFOLLOW);
405 __check_one_fd (STDOUT_FILENO, O_RDWR | O_NOFOLLOW);
406 __check_one_fd (STDERR_FILENO, O_RDWR | O_NOFOLLOW);
407 _pe_secure = 1 ;
409 else
410 _pe_secure = 0 ;
411 #endif
413 __uclibc_progname = *argv;
414 #if defined __UCLIBC_HAS___PROGNAME__ || (defined __USE_GNU && defined __UCLIBC_HAS_PROGRAM_INVOCATION_NAME__)
415 if (*argv != NULL) {
416 __progname_full = *argv;
417 __progname = strrchr(*argv, '/');
418 if (__progname != NULL)
419 ++__progname;
420 else
421 __progname = *argv;
423 #endif
425 #ifdef __UCLIBC_CTOR_DTOR__
426 /* Arrange for the application's dtors to run before we exit. */
427 __app_fini = app_fini;
429 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
430 * by __app_init. */
431 # if !defined (SHARED) && !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
432 /* For dynamically linked executables the preinit array is executed by
433 the dynamic linker (before initializing any shared object).
434 For static executables, preinit happens rights before init. */
436 const size_t size = __preinit_array_end - __preinit_array_start;
437 size_t i;
438 for (i = 0; i < size; i++)
439 (*__preinit_array_start [i]) ();
441 # endif
442 /* Run all the application's ctors now. */
443 if (app_init!=NULL) {
444 app_init();
446 /* If __UCLIBC_FORMAT_SHARED_FLAT__, all array initialisation is handled
447 * by __app_init. */
448 # ifdef SHARED
449 _dl_app_init_array();
450 # elif !defined (__UCLIBC_FORMAT_SHARED_FLAT__)
452 const size_t size = __init_array_end - __init_array_start;
453 size_t i;
454 for (i = 0; i < size; i++)
455 (*__init_array_start [i]) ();
457 # endif
458 #endif
460 /* Note: It is possible that any initialization done above could
461 * have resulted in errno being set nonzero, so set it to 0 before
462 * we call main.
464 if (likely(not_null_ptr(__errno_location)))
465 *(__errno_location()) = 0;
467 /* Set h_errno to 0 as well */
468 if (likely(not_null_ptr(__h_errno_location)))
469 *(__h_errno_location()) = 0;
471 #if defined HAVE_CLEANUP_JMP_BUF && defined __UCLIBC_HAS_THREADS_NATIVE__
472 /* Memory for the cancellation buffer. */
473 struct pthread_unwind_buf unwind_buf;
475 int not_first_call;
476 not_first_call =
477 setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf);
478 if (__builtin_expect (! not_first_call, 1))
480 struct pthread *self = THREAD_SELF;
482 /* Store old info. */
483 unwind_buf.priv.data.prev = THREAD_GETMEM (self, cleanup_jmp_buf);
484 unwind_buf.priv.data.cleanup = THREAD_GETMEM (self, cleanup);
486 /* Store the new cleanup handler info. */
487 THREAD_SETMEM (self, cleanup_jmp_buf, &unwind_buf);
489 /* Run the program. */
490 result = main (argc, argv, __environ);
492 else
494 /* Remove the thread-local data. */
495 __nptl_deallocate_tsd ();
497 /* One less thread. Decrement the counter. If it is zero we
498 terminate the entire process. */
499 result = 0;
500 unsigned int *const ptr = &__nptl_nthreads;
502 if (! atomic_decrement_and_test (ptr))
503 /* Not much left to do but to exit the thread, not the process. */
504 __exit_thread_inline (0);
507 exit (result);
508 #else
510 * Finally, invoke application's main and then exit.
512 exit (main (argc, argv, __environ));
513 #endif