Skip to content

Commit

Permalink
Merge pull request #10472 from gasche/caml_sys_random_seed
Browse files Browse the repository at this point in the history
Refactor `caml_sys_random_seed`
  • Loading branch information
gasche committed Jun 30, 2021
2 parents e1a37e1 + 46ec3be commit 424a2f6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
3 changes: 3 additions & 0 deletions Changes
Expand Up @@ -53,6 +53,9 @@ Working version
type
(Nicolas Chataing, review by Gabriel Scherer)

- #10472: refactor caml_sys_random_seed to ease future Multicore changes
(Gabriel Scherer, review by Xavier Leroy)

### Build system:

### Bug fixes:
Expand Down
45 changes: 27 additions & 18 deletions runtime/sys.c
Expand Up @@ -561,18 +561,12 @@ CAMLprim value caml_sys_time(value unit)

#ifdef _WIN32
extern int caml_win32_random_seed (intnat data[16]);
#endif

CAMLprim value caml_sys_random_seed (value unit)
{
intnat data[16];
int n, i;
value res;
#ifdef _WIN32
n = caml_win32_random_seed(data);
#else
int caml_unix_random_seed(intnat data[16])
{
int fd;
n = 0;
int n = 0;

/* Try /dev/urandom first */
fd = open("/dev/urandom", O_RDONLY, 0);
if (fd != -1) {
Expand All @@ -582,22 +576,37 @@ CAMLprim value caml_sys_random_seed (value unit)
while (nread > 0) data[n++] = buffer[--nread];
}
/* If the read from /dev/urandom fully succeeded, we now have 96 bits
of good random data and can stop here. Otherwise, complement
whatever we got (probably nothing) with some not-very-random data. */
if (n < 12) {
of good random data and can stop here. */
if (n >= 12) return n;
/* Otherwise, complement whatever we got (probably nothing)
with some not-very-random data. */
{
#ifdef HAS_GETTIMEOFDAY
struct timeval tv;
gettimeofday(&tv, NULL);
data[n++] = tv.tv_usec;
data[n++] = tv.tv_sec;
if (n < 16) data[n++] = tv.tv_usec;
if (n < 16) data[n++] = tv.tv_sec;
#else
data[n++] = time(NULL);
if (n < 16) data[n++] = time(NULL);
#endif
#ifdef HAS_UNISTD
data[n++] = getpid();
data[n++] = getppid();
if (n < 16) data[n++] = getpid();
if (n < 16) data[n++] = getppid();
#endif
return n;
}
}
#endif

CAMLprim value caml_sys_random_seed (value unit)
{
intnat data[16];
int n, i;
value res;
#ifdef _WIN32
n = caml_win32_random_seed(data);
#else
n = caml_unix_random_seed(data);
#endif
/* Convert to an OCaml array of ints */
res = caml_alloc_small(n, 0);
Expand Down

0 comments on commit 424a2f6

Please sign in to comment.