1 #include <elf.h>
2 #include <poll.h>
3 #include <fcntl.h>
4 #include <signal.h>
5 #include <unistd.h>
6 #include "atomic.h"
7 #include "libc.h"
8
dummy(void)9 static void dummy(void) {}
10 weak_alias(dummy, _init);
11
12 extern weak hidden void (*const __init_array_start)(void), (*const __init_array_end)(void);
13
dummy1(void * p)14 static void dummy1(void *p) {}
15 weak_alias(dummy1, __init_ssp);
16
17 #define AUX_CNT 38
18
19 #ifdef __GNUC__
20 __attribute__((__noinline__))
21 #endif
__init_libc(char ** envp,char * pn)22 void __init_libc(char **envp, char *pn)
23 {
24 size_t i, *auxv, aux[AUX_CNT] = { 0 };
25 __environ = envp;
26 for (i=0; envp[i]; i++);
27 libc.auxv = auxv = (void *)(envp+i+1);
28 for (i=0; auxv[i]; i+=2) if (auxv[i]<AUX_CNT) aux[auxv[i]] = auxv[i+1];
29 __hwcap = aux[AT_HWCAP];
30 if (aux[AT_SYSINFO]) __sysinfo = aux[AT_SYSINFO];
31 libc.page_size = aux[AT_PAGESZ];
32
33 if (!pn) pn = (void*)aux[AT_EXECFN];
34 if (!pn) pn = "";
35 __progname = __progname_full = pn;
36 for (i=0; pn[i]; i++) if (pn[i]=='/') __progname = pn+i+1;
37
38 __init_tls(aux);
39 __init_ssp((void *)aux[AT_RANDOM]);
40 }
41
libc_start_init(void)42 static void libc_start_init(void)
43 {
44 _init();
45 uintptr_t a = (uintptr_t)&__init_array_start;
46 for (; a<(uintptr_t)&__init_array_end; a+=sizeof(void(*)()))
47 (*(void (**)(void))a)();
48 }
49
50 weak_alias(libc_start_init, __libc_start_init);
51
52 typedef int lsm2_fn(int (*)(int,char **,char **), int, char **);
53 static lsm2_fn libc_start_main_stage2;
54
__libc_start_main(int (* main)(int,char **,char **),int argc,char ** argv)55 int __libc_start_main(int (*main)(int,char **,char **), int argc, char **argv)
56 {
57 char **envp = argv+argc+1;
58
59 /* External linkage, and explicit noinline attribute if available,
60 * are used to prevent the stack frame used during init from
61 * persisting for the entire process lifetime. */
62 __init_libc(envp, argv[0]);
63
64 /* Barrier against hoisting application code or anything using ssp
65 * or thread pointer prior to its initialization above. */
66 lsm2_fn *stage2 = libc_start_main_stage2;
67 __asm__ ( "" : "+r"(stage2) : : "memory" );
68 return stage2(main, argc, argv);
69 }
70
libc_start_main_stage2(int (* main)(int,char **,char **),int argc,char ** argv)71 static int libc_start_main_stage2(int (*main)(int,char **,char **), int argc, char **argv)
72 {
73 char **envp = argv+argc+1;
74 __libc_start_init();
75
76 /* Pass control to the application */
77 exit(main(argc, argv, envp));
78 return 0;
79 }
80