From c84a25e14882a356bc37647a2acf1b6a9127283b Mon Sep 17 00:00:00 2001 From: nobu Date: Sun, 10 Feb 2019 10:42:50 +0000 Subject: [PATCH] random.c: unify syscall with getrandom git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@67046 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- random.c | 48 ++++++++++++++---------------------------------- 1 file changed, 14 insertions(+), 34 deletions(-) diff --git a/random.c b/random.c index a21f684325..2e557fd1b2 100644 --- a/random.c +++ b/random.c @@ -320,6 +320,19 @@ fill_random_bytes_urandom(void *seed, size_t size) # define fill_random_bytes_urandom(seed, size) -1 #endif +#if defined HAVE_GETRANDOM +# include +#elif defined __linux__ && defined __NR_getrandom +# include + +# ifndef GRND_NONBLOCK +# define GRND_NONBLOCK 0x0001 /* not defined in musl libc */ +# endif +# define getrandom(ptr, size, flags) \ + (ssize_t)syscall(__NR_getrandom, (ptr), (size), (flags)) +# define HAVE_GETRANDOM 1 +#endif + #if 0 #elif defined MAC_OS_X_VERSION_10_7 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7 #include @@ -391,51 +404,18 @@ fill_random_bytes_syscall(void *seed, size_t size, int unused) return 0; } #elif defined HAVE_GETRANDOM -#include - static int fill_random_bytes_syscall(void *seed, size_t size, int need_secure) { static rb_atomic_t try_syscall = 1; if (try_syscall) { - ssize_t ret; - size_t offset = 0; - int flags = 0; - if (!need_secure) - flags = GRND_NONBLOCK; - do { - errno = 0; - ret = getrandom(((char*)seed) + offset, size - offset, flags); - if (ret == -1) { - ATOMIC_SET(try_syscall, 0); - return -1; - } - offset += (size_t)ret; - } while(offset < size); - return 0; - } - return -1; -} -#elif defined __linux__ && defined __NR_getrandom -#include - -# ifndef GRND_NONBLOCK -# define GRND_NONBLOCK 0x0001 /* not defined in musl libc */ -# endif - -static int -fill_random_bytes_syscall(void *seed, size_t size, int need_secure) -{ - static rb_atomic_t try_syscall = 1; - if (try_syscall) { - long ret; size_t offset = 0; int flags = 0; if (!need_secure) flags = GRND_NONBLOCK; do { errno = 0; - ret = syscall(__NR_getrandom, ((char*)seed) + offset, size - offset, flags); + ssize_t ret = getrandom(((char*)seed) + offset, size - offset, flags); if (ret == -1) { ATOMIC_SET(try_syscall, 0); return -1;