From 8bc1f1b63e01792df423c9ff845dfe7f389a27a9 Mon Sep 17 00:00:00 2001 From: Beckett Normington Date: Fri, 25 Aug 2023 12:20:39 -0400 Subject: [PATCH] LibC: Add `drand48`, `srand48` These functions are required for the `perl5` port's random function to operate correctly. As a bonus, this allows us to remove a nasty patch that replaces `drand48` with `random`. --- Userland/Libraries/LibC/stdlib.cpp | 18 ++++++++++++++++++ Userland/Libraries/LibC/stdlib.h | 2 ++ 2 files changed, 20 insertions(+) diff --git a/Userland/Libraries/LibC/stdlib.cpp b/Userland/Libraries/LibC/stdlib.cpp index d1e7139461..e9bccaa120 100644 --- a/Userland/Libraries/LibC/stdlib.cpp +++ b/Userland/Libraries/LibC/stdlib.cpp @@ -657,6 +657,7 @@ int ptsname_r(int fd, char* buffer, size_t size) } static unsigned long s_next_rand = 1; +static long s_next_rand48 = 0; // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html int rand() @@ -671,6 +672,23 @@ void srand(unsigned seed) s_next_rand = seed; } +// https://pubs.opengroup.org/onlinepubs/9699919799/functions/drand48.html +double drand48() +{ + constexpr u64 a = 0x5DEECE66DULL; + constexpr u64 c = 0xBULL; + constexpr u64 m = 1ULL << 48; + + s_next_rand48 = (a * s_next_rand48 + c) & (m - 1); + return static_cast(s_next_rand48) / m; +} + +// https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand48.html +void srand48(long seed) +{ + s_next_rand48 = (seed & 0xFFFFFFFF) << 16 | 0x330E; +} + // https://pubs.opengroup.org/onlinepubs/9699919799/functions/abs.html int abs(int i) { diff --git a/Userland/Libraries/LibC/stdlib.h b/Userland/Libraries/LibC/stdlib.h index 8b1f937d35..cfcd544526 100644 --- a/Userland/Libraries/LibC/stdlib.h +++ b/Userland/Libraries/LibC/stdlib.h @@ -78,6 +78,8 @@ __attribute__((noreturn)) void _Exit(int status); #define RAND_MAX 32767 int rand(void); void srand(unsigned seed); +double drand48(void); +void srand48(long seed); long int random(void); void srandom(unsigned seed);