2022-10-11 21:08:46 +02:00
|
|
|
#include <errno.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2022-10-12 17:14:49 +02:00
|
|
|
#include <unistd.h>
|
2022-10-11 21:08:46 +02:00
|
|
|
|
2022-10-12 20:41:55 +02:00
|
|
|
static void terminate_libc()
|
|
|
|
{
|
|
|
|
fclose(stdout);
|
|
|
|
fclose(stderr);
|
2022-10-19 20:43:04 +02:00
|
|
|
fclose(stdin);
|
2022-10-12 20:41:55 +02:00
|
|
|
}
|
|
|
|
|
2022-10-15 16:46:54 +02:00
|
|
|
static void initialize_random()
|
|
|
|
{
|
|
|
|
unsigned int seed = 3735928559U;
|
|
|
|
|
|
|
|
FILE* fp = fopen("/dev/random", "rw");
|
|
|
|
if (!fp)
|
|
|
|
{
|
|
|
|
errno = 0;
|
|
|
|
goto failed_to_read_dev_random;
|
|
|
|
}
|
|
|
|
|
|
|
|
fread(&seed, sizeof(seed), 1, fp);
|
|
|
|
if (ferror(fp))
|
|
|
|
{
|
|
|
|
errno = 0;
|
|
|
|
fclose(fp);
|
|
|
|
goto failed_to_read_dev_random;
|
|
|
|
}
|
|
|
|
|
|
|
|
fclose(fp);
|
|
|
|
|
|
|
|
failed_to_read_dev_random:
|
|
|
|
srand(seed); // If we failed, this will be seeded with a known value. Else, it will be seeded with a random value
|
|
|
|
// from the kernel.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-14 19:36:20 +02:00
|
|
|
static void check_for_file(int fd, FILE** target_stream, const char* path, const char* mode)
|
2022-10-11 21:08:46 +02:00
|
|
|
{
|
2022-10-14 19:36:20 +02:00
|
|
|
if (lseek(fd, 0, SEEK_CUR) < 0)
|
2022-10-12 20:19:45 +02:00
|
|
|
{
|
2022-10-14 19:36:20 +02:00
|
|
|
if (errno == EBADF) *target_stream = fopen(path, mode);
|
2022-10-12 20:19:45 +02:00
|
|
|
else
|
2022-10-14 21:26:46 +02:00
|
|
|
exit(-127);
|
|
|
|
if (!*target_stream) exit(-127);
|
2022-10-12 20:19:45 +02:00
|
|
|
errno = 0;
|
|
|
|
}
|
2022-10-14 19:36:20 +02:00
|
|
|
else { *target_stream = fdopen(fd, mode); }
|
|
|
|
}
|
|
|
|
|
|
|
|
extern "C" void initialize_libc()
|
|
|
|
{
|
2022-10-19 20:43:04 +02:00
|
|
|
check_for_file(STDIN_FILENO, &stdin, "/dev/kbd", "r");
|
2022-10-14 21:24:18 +02:00
|
|
|
check_for_file(STDOUT_FILENO, &stdout, "/dev/console", "rw");
|
|
|
|
check_for_file(STDERR_FILENO, &stderr, "/dev/console", "rw");
|
2022-10-15 16:46:54 +02:00
|
|
|
|
|
|
|
initialize_random();
|
2022-10-12 20:41:55 +02:00
|
|
|
atexit(terminate_libc);
|
2022-10-11 21:08:46 +02:00
|
|
|
}
|