impose barrier between thread pointer setup and use for static linking
[musl] / src / env / __libc_start_main.c
1 #include <elf.h>
2 #include <poll.h>
3 #include <fcntl.h>
4 #include <signal.h>
5 #include <unistd.h>
6 #include "syscall.h"
7 #include "atomic.h"
8 #include "libc.h"
9
10 static void dummy(void) {}
11 weak_alias(dummy, _init);
12
13 extern weak hidden void (*const __init_array_start)(void), (*const __init_array_end)(void);
14
15 static void dummy1(void *p) {}
16 weak_alias(dummy1, __init_ssp);
17
18 #define AUX_CNT 38
19
20 void __init_libc(char **envp, char *pn)
21 {
22         size_t i, *auxv, aux[AUX_CNT] = { 0 };
23         __environ = envp;
24         for (i=0; envp[i]; i++);
25         libc.auxv = auxv = (void *)(envp+i+1);
26         for (i=0; auxv[i]; i+=2) if (auxv[i]<AUX_CNT) aux[auxv[i]] = auxv[i+1];
27         __hwcap = aux[AT_HWCAP];
28         __sysinfo = aux[AT_SYSINFO];
29         libc.page_size = aux[AT_PAGESZ];
30
31         if (!pn) pn = (void*)aux[AT_EXECFN];
32         if (!pn) pn = "";
33         __progname = __progname_full = pn;
34         for (i=0; pn[i]; i++) if (pn[i]=='/') __progname = pn+i+1;
35
36         __init_tls(aux);
37         __init_ssp((void *)aux[AT_RANDOM]);
38
39         if (aux[AT_UID]==aux[AT_EUID] && aux[AT_GID]==aux[AT_EGID]
40                 && !aux[AT_SECURE]) return;
41
42         struct pollfd pfd[3] = { {.fd=0}, {.fd=1}, {.fd=2} };
43         int r =
44 #ifdef SYS_poll
45         __syscall(SYS_poll, pfd, 3, 0);
46 #else
47         __syscall(SYS_ppoll, pfd, 3, &(struct timespec){0}, 0, _NSIG/8);
48 #endif
49         if (r<0) a_crash();
50         for (i=0; i<3; i++) if (pfd[i].revents&POLLNVAL)
51                 if (__sys_open("/dev/null", O_RDWR)<0)
52                         a_crash();
53         libc.secure = 1;
54 }
55
56 static void libc_start_init(void)
57 {
58         _init();
59         uintptr_t a = (uintptr_t)&__init_array_start;
60         for (; a<(uintptr_t)&__init_array_end; a+=sizeof(void(*)()))
61                 (*(void (**)(void))a)();
62 }
63
64 weak_alias(libc_start_init, __libc_start_init);
65
66 static int libc_start_main_stage2(int (*)(int,char **,char **), int, char **);
67
68 int __libc_start_main(int (*main)(int,char **,char **), int argc, char **argv)
69 {
70         char **envp = argv+argc+1;
71
72         __init_libc(envp, argv[0]);
73
74         /* Barrier against hoisting application code or anything using ssp
75          * or thread pointer prior to its initialization above. */
76         int (*stage2)();
77         __asm__ ( "" : "=r"(stage2) : "r"(libc_start_main_stage2) : "memory" );
78         return stage2(main, argc, argv);
79 }
80
81 static int libc_start_main_stage2(int (*main)(int,char **,char **), int argc, char **argv)
82 {
83         char **envp = argv+argc+1;
84         __libc_start_init();
85
86         /* Pass control to the application */
87         exit(main(argc, argv, envp));
88         return 0;
89 }