unify static and dynamic libc init/fini code paths
[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 "syscall.h"
6 #include "atomic.h"
7 #include "libc.h"
8
9 void __init_tls(size_t *);
10
11 extern void _init() __attribute__((weak));
12 extern void (*const __init_array_start)() __attribute__((weak));
13 extern void (*const __init_array_end)() __attribute__((weak));
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) {
32                 __progname = __progname_full = pn;
33                 for (i=0; pn[i]; i++) if (pn[i]=='/') __progname = pn+i+1;
34         }
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 #ifdef SYS_poll
44         __syscall(SYS_poll, pfd, 3, 0);
45 #else
46         __syscall(SYS_ppoll, pfd, 3, &(struct timespec){0}, 0, _NSIG/8);
47 #endif
48         for (i=0; i<3; i++) if (pfd[i].revents&POLLNVAL)
49                 if (__sys_open("/dev/null", O_RDWR)<0)
50                         a_crash();
51         libc.secure = 1;
52 }
53
54 static void libc_start_init(void)
55 {
56         if (_init) _init();
57         uintptr_t a = (uintptr_t)&__init_array_start;
58         for (; a<(uintptr_t)&__init_array_end; a+=sizeof(void(*)()))
59                 (*(void (**)())a)();
60 }
61
62 weak_alias(libc_start_init, __libc_start_init);
63
64 int __libc_start_main(int (*main)(int,char **,char **), int argc, char **argv)
65 {
66         char **envp = argv+argc+1;
67
68         __init_libc(envp, argv[0]);
69         __libc_start_init();
70
71         /* Pass control to the application */
72         exit(main(argc, argv, envp));
73         return 0;
74 }