util/rand_xor: use getrandom() when available
authorEmmanuel Gil Peyrot <linkmauve@linkmauve.fr>
Wed, 18 Sep 2019 11:20:57 +0000 (13:20 +0200)
committerEmmanuel Gil Peyrot <linkmauve@linkmauve.fr>
Fri, 15 May 2020 11:37:20 +0000 (13:37 +0200)
This function has been added in glibc 2.25, and the related syscall in
Linux 3.17, in order to avoid requiring the /dev/urandom to exist, and
doing the open()/read()/close() dance on it.

We pass GRND_NONBLOCK so that it doesn’t block if not enough entropy has
been gathered to initialise the /dev/urandom source, and fallback to the
next source in any error case.

Signed-off-by: Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
Reviewed-by: Eric Engestrom <eric.engestrom@intel.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/2026>

meson.build
src/util/rand_xor.c

index ba4fdb2..1a20784 100644 (file)
@@ -1163,7 +1163,7 @@ foreach h : ['xlocale.h', 'sys/sysctl.h', 'linux/futex.h', 'endian.h', 'dlfcn.h'
   endif
 endforeach
 
-foreach f : ['strtof', 'mkostemp', 'timespec_get', 'memfd_create', 'random_r', 'flock', 'strtok_r']
+foreach f : ['strtof', 'mkostemp', 'timespec_get', 'memfd_create', 'random_r', 'flock', 'strtok_r', 'getrandom']
   if cc.has_function(f)
     pre_args += '-DHAVE_@0@'.format(f.to_upper())
   endif
index de04bbc..31612d5 100644 (file)
@@ -23,6 +23,9 @@
  */
 
 #if defined(__linux__)
+#if defined(HAVE_GETRANDOM)
+#include <sys/random.h>
+#endif
 #include <sys/file.h>
 #include <unistd.h>
 #include <fcntl.h>
@@ -58,11 +61,18 @@ s_rand_xorshift128plus(uint64_t *seed, bool randomised_seed)
       goto fixed_seed;
 
 #if defined(__linux__)
+   size_t seed_size = sizeof(uint64_t) * 2;
+
+#if defined(HAVE_GETRANDOM)
+   ssize_t ret = getrandom(seed, seed_size, GRND_NONBLOCK);
+   if (ret == seed_size)
+      return;
+#endif
+
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0)
       goto fixed_seed;
 
-   size_t seed_size = sizeof(uint64_t) * 2;
    if (read(fd, seed, seed_size) != seed_size) {
       close(fd);
       goto fixed_seed;