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