Skip to content

Commit

Permalink
[C] Fix aeron_randomised_int32 on Windows (#854)
Browse files Browse the repository at this point in the history
- rand() was not seeded and always produced the same sequence
 - rand() * INT_MAX would always cause an overflow
 - Use rand_s instead of rand for better randomness
   and to avoid the dependency on a seed
  • Loading branch information
ltrzesniewski authored Feb 13, 2020
1 parent 6511773 commit 6425b6e
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions aeron-driver/src/main/c/aeron_driver.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "aeron_windows.h"
#if defined(AERON_COMPILER_MSVC) && defined(AERON_CPU_X64)

#define _CRT_RAND_S
#include <io.h>
#include <direct.h>
#include <process.h>
Expand Down Expand Up @@ -146,9 +147,18 @@ int32_t aeron_randomised_int32()
fprintf(stderr, "Failed to read from aeron_dev_random (%d): %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}

#elif defined(AERON_COMPILER_MSVC)
uint32_t value;
if (0 == rand_s(&value))
{
memcpy(&result, &value, sizeof(int32_t));
}
else
{
result = (int32_t)(rand() / (double)RAND_MAX * INT_MAX);
}
#else
result = rand() * INT_MAX;
result = (int32_t)(rand() / (double)RAND_MAX * INT_MAX);
#endif
return result;
}
Expand Down

0 comments on commit 6425b6e

Please # to comment.