Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor caml_sys_random_seed #10472

Merged
merged 2 commits into from
Jun 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
45 changes: 27 additions & 18 deletions runtime/sys.c
Original file line number Diff line number Diff line change
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();
xavierleroy marked this conversation as resolved.
Show resolved Hide resolved
#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