From e341394643437cf46be2a6c4225d8131eec1efdc Mon Sep 17 00:00:00 2001 From: Frantisek Sumsal Date: Mon, 4 Jul 2022 23:00:01 +0200 Subject: [PATCH] rand: accept seed for rand()/srandom() from the outside So we can use reproducible seeds in tests to make reproducing test crashes easier. --- src/dfuzzer.c | 2 +- src/rand.c | 6 +++--- src/rand.h | 6 +----- test/test-rand.c | 12 ++++++++++-- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/dfuzzer.c b/src/dfuzzer.c index 1ba2819..9034f2a 100644 --- a/src/dfuzzer.c +++ b/src/dfuzzer.c @@ -231,7 +231,7 @@ static int df_fuzz(GDBusConnection *dcon, const char *name, const char *object, int rv = DF_BUS_OK; // initialization of random module - df_rand_init(); + df_rand_init(time(NULL)); // Sanity check fuzzing target if (isempty(name) || isempty(object) || isempty(interface)) { diff --git a/src/rand.c b/src/rand.c index 281abd2..8632868 100644 --- a/src/rand.c +++ b/src/rand.c @@ -39,10 +39,10 @@ static struct external_dictionary df_external_dictionary; * numbers generators. * @param buf_size Maximum buffer size for generated strings (in Bytes) */ -void df_rand_init() +void df_rand_init(unsigned int seed) { - srand(time(NULL)); // for int rand() - srandom(time(NULL)); // for long int random() + srand(seed); + srandom(seed); } int df_rand_load_external_dictionary(const char *filename) diff --git a/src/rand.h b/src/rand.h index 247f11d..c7ee8dc 100644 --- a/src/rand.h +++ b/src/rand.h @@ -30,11 +30,7 @@ struct external_dictionary { char **strings; }; -/** - * @function Initializes global flag variables and seeds pseudo-random - * numbers generators. - */ -void df_rand_init(); +void df_rand_init(unsigned int seed); int df_rand_load_external_dictionary(const char *filename); GVariant *df_generate_random_basic(const GVariantType *type, guint64 iteration); diff --git a/test/test-rand.c b/test/test-rand.c index 3bbd4ec..11a931f 100644 --- a/test/test-rand.c +++ b/test/test-rand.c @@ -109,8 +109,16 @@ static void test_df_rand_GVariant(void) int main(int argc, char *argv[]) { g_test_init(&argc, &argv, NULL); - /* Init our internal pseudo-random number generators */ - df_rand_init(); + /* Init our internal pseudo-random number generators + * + * Since we can't access the g_test_*() seed directly, let's use one + * of the g_test_rand*() functions that generate reproducible numbers + * (using the internal seed), so a possible test crash can be later + * reproduced using the `--seed xxx` option + * + * See: https://docs.gtk.org/glib/func.test_rand_int.html + * */ + df_rand_init(g_test_rand_int()); g_test_add_func("/df_rand/df_rand_unichar", test_df_rand_unichar); g_test_add_func("/df_rand/df_rand_string", test_df_rand_string);