Skip to content

Commit

Permalink
rand: accept seed for rand()/srandom() from the outside
Browse files Browse the repository at this point in the history
So we can use reproducible seeds in tests to make reproducing test
crashes easier.
  • Loading branch information
mrc0mmand committed Jul 4, 2022
1 parent 6059023 commit e341394
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/dfuzzer.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
6 changes: 3 additions & 3 deletions src/rand.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 1 addition & 5 deletions src/rand.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 10 additions & 2 deletions test/test-rand.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit e341394

Please sign in to comment.