From 18f1f8b7ca7e41f7cfad5fb737860affb3d51965 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 15 Oct 2022 16:31:08 +0200 Subject: [PATCH] Add VERY HACKY rand() implementation. --- libs/libc/include/stdlib.h | 6 ++++++ libs/libc/src/rand.cpp | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 libs/libc/src/rand.cpp diff --git a/libs/libc/include/stdlib.h b/libs/libc/include/stdlib.h index eee533e9..90a5ac48 100644 --- a/libs/libc/include/stdlib.h +++ b/libs/libc/include/stdlib.h @@ -50,6 +50,12 @@ extern "C" * is undefined behavior. */ void free(void* ptr); + /* Returns a random number. */ + int rand(void); + + /* Does nothing. */ + void srand(unsigned int seed); + #ifdef __cplusplus } #endif diff --git a/libs/libc/src/rand.cpp b/libs/libc/src/rand.cpp new file mode 100644 index 00000000..eea3ae4e --- /dev/null +++ b/libs/libc/src/rand.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +static FILE* randfp = nullptr; + +void close_randfp() +{ + fclose(randfp); +} + +extern "C" +{ + int rand() // FIXME: This function is a dirty and extremely hacky way to get going, /dev/random should only be used + // for initial seeding, userspace should do their own random calculations. + { + if (!randfp) + { + randfp = fopen("/dev/random", "rw"); + assert(randfp != nullptr); + atexit(close_randfp); + } + int result; + fread(&result, sizeof(result), 1, randfp); + if (ferror(randfp)) + { + perror("read(randfp)"); + abort(); + } + return result; + } + + void srand(unsigned int) + { + return; + } +} \ No newline at end of file