Skip to content

Commit

Permalink
caml_unix_random_seed: clarify fallback logic
Browse files Browse the repository at this point in the history
Hopefully the new structure should make it easy to add new elements to
the random seed in the non-/dev/urandom case, in particular a domain
identifier for Multicore OCaml.
  • Loading branch information
gasche committed Jun 28, 2021
1 parent 54bedf4 commit 46ec3be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
3 changes: 3 additions & 0 deletions Changes
Original file line number Diff line number Diff line change
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
21 changes: 12 additions & 9 deletions runtime/sys.c
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ int caml_unix_random_seed(intnat data[16])
{
int fd;
int n = 0;

/* Try /dev/urandom first */
fd = open("/dev/urandom", O_RDONLY, 0);
if (fd != -1) {
Expand All @@ -575,23 +576,25 @@ int caml_unix_random_seed(intnat data[16])
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;
}
return n;
}
#endif

Expand Down

0 comments on commit 46ec3be

Please sign in to comment.