From 67204063f9311ebb6b86f59ac5af16605c307ef7 Mon Sep 17 00:00:00 2001 From: Ray Strode Date: Sun, 3 Dec 2023 18:59:18 -0500 Subject: [PATCH] ply-utils: Add function for getting random number 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 | 22 ++++++++++++++++++++++ src/libply/ply-utils.h | 2 ++ 2 files changed, 24 insertions(+) diff --git a/src/libply/ply-utils.c b/src/libply/ply-utils.c index dd6294f6..abbc8b5a 100644 --- a/src/libply/ply-utils.c +++ b/src/libply/ply-utils.c @@ -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: */ diff --git a/src/libply/ply-utils.h b/src/libply/ply-utils.h index 8000632b..289d3a3f 100644 --- a/src/libply/ply-utils.h +++ b/src/libply/ply-utils.h @@ -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 */ -- 2.47.3