]> git.ipfire.org Git - thirdparty/plymouth.git/commitdiff
ply-utils: Add function for getting random number
authorRay Strode <rstrode@redhat.com>
Sun, 3 Dec 2023 23:59:18 +0000 (18:59 -0500)
committerRay Strode <rstrode@redhat.com>
Mon, 4 Dec 2023 10:48:06 +0000 (05:48 -0500)
rand() and srand() are we use now and it's not working out too well
because we're seeding correctly in a number of places.

This commit adds one function to do it better.

Problem spotted by @emperor06

src/libply/ply-utils.c
src/libply/ply-utils.h

index dd6294f69df8a581708c4f237b042481797e144e..abbc8b5abde8a911ae2f7184a5c26d756c6bd615 100644 (file)
@@ -1211,4 +1211,26 @@ ply_is_secure_boot_enabled (void)
         return is_secure_boot_enabled;
 }
 
+long
+ply_get_random_number (long lower_bound,
+                       long range)
+{
+        static bool seed_initialized = false;
+        long offset;
+
+        if (!seed_initialized) {
+                struct timespec now = { 0L, /* zero-filled */ };
+
+                clock_gettime (CLOCK_TAI, &now);
+                srand48 (now.tv_nsec);
+                seed_initialized = true;
+        }
+
+        offset = mrand48 ();
+
+        offset = labs (offset) % range;
+
+        return lower_bound + offset;
+}
+
 /* vim: set ts=4 sw=4 expandtab autoindent cindent cino={.5s,(0: */
index 8000632b8dc4407a7f673442eb83ef3b804c6477..289d3a3ffeabaeac2fedb9eb24454031efba1d95 100644 (file)
@@ -160,6 +160,8 @@ double ply_strtod (const char *str);
 
 bool ply_is_secure_boot_enabled (void);
 
+long ply_get_random_number (long lower_bound, long range);
+
 #endif
 
 #endif /* PLY_UTILS_H */