toaruos/libc/main.c

107 lines
1.9 KiB
C
Raw Normal View History

2018-02-25 08:13:54 +03:00
#include <stdint.h>
#include <stddef.h>
2018-08-14 08:39:48 +03:00
#include <stdlib.h>
2018-02-25 08:13:54 +03:00
#include <syscall.h>
#include <syscall_nums.h>
DEFN_SYSCALL1(exit, SYS_EXT, int);
DEFN_SYSCALL2(sleepabs, SYS_SLEEPABS, unsigned long, unsigned long);
2018-02-25 08:13:54 +03:00
extern void _init();
extern void _fini();
char ** environ = NULL;
2018-02-25 11:14:43 +03:00
int _environ_size = 0;
char * _argv_0 = NULL;
2018-10-12 09:03:22 +03:00
int __libc_debug = 0;
2018-02-25 08:13:54 +03:00
char ** __argv = NULL;
extern char ** __get_argv(void) {
return __argv;
}
extern void __stdio_init_buffers(void);
2021-04-07 13:08:06 +03:00
extern void __stdio_cleanup(void);
2018-02-25 08:13:54 +03:00
void _exit(int val){
_fini();
2021-04-07 13:08:06 +03:00
__stdio_cleanup();
2018-02-25 08:13:54 +03:00
syscall_exit(val);
__builtin_unreachable();
}
extern void __make_tls(void);
__attribute__((constructor))
static void _libc_init(void) {
__make_tls();
__stdio_init_buffers();
2018-02-25 08:13:54 +03:00
unsigned int x = 0;
unsigned int nulls = 0;
for (x = 0; 1; ++x) {
if (!__get_argv()[x]) {
2018-02-25 08:13:54 +03:00
++nulls;
if (nulls == 2) {
break;
}
continue;
}
if (nulls == 1) {
environ = &__get_argv()[x];
2018-02-25 08:13:54 +03:00
break;
}
}
2018-08-14 08:39:48 +03:00
if (!environ) {
environ = malloc(sizeof(char *) * 4);
environ[0] = NULL;
environ[1] = NULL;
environ[2] = NULL;
environ[3] = NULL;
_environ_size = 4;
} else {
/* Find actual size */
int size = 0;
char ** tmp = environ;
while (*tmp) {
size++;
tmp++;
}
if (size < 4) {
_environ_size = 4;
} else {
/* Multiply by two */
_environ_size = size * 2;
}
char ** new_environ = malloc(sizeof(char*) * _environ_size);
int i = 0;
while (i < _environ_size && environ[i]) {
new_environ[i] = environ[i];
i++;
}
while (i < _environ_size) {
new_environ[i] = NULL;
i++;
}
environ = new_environ;
}
2018-10-12 09:03:22 +03:00
if (getenv("__LIBC_DEBUG")) __libc_debug = 1;
_argv_0 = __get_argv()[0];
}
void pre_main(int (*main)(int,char**), int argc, char * argv[]) {
if (!__get_argv()) {
/* Statically loaded, must set __argv so __get_argv() works */
__argv = argv;
}
2018-02-25 08:13:54 +03:00
_init();
2018-09-15 10:26:45 +03:00
exit(main(argc, argv));
2018-02-25 08:13:54 +03:00
}