[libcxx] r319523 - [libcxx] Support getentropy as a source of randomness for std::random_device

Petr Hosek via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 30 22:34:33 PST 2017


Author: phosek
Date: Thu Nov 30 22:34:33 2017
New Revision: 319523

URL: http://llvm.org/viewvc/llvm-project?rev=319523&view=rev
Log:
[libcxx] Support getentropy as a source of randomness for std::random_device

Use this source use on Fuchsia where this is the oficially way
to obtain randomness. This could be also used on other platforms
that already support getentropy such as *BSD or Linux.

Differential Revision: https://reviews.llvm.org/D40319

Modified:
    libcxx/trunk/include/__config
    libcxx/trunk/src/random.cpp

Modified: libcxx/trunk/include/__config
URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/__config?rev=319523&r1=319522&r2=319523&view=diff
==============================================================================
--- libcxx/trunk/include/__config (original)
+++ libcxx/trunk/include/__config Thu Nov 30 22:34:33 2017
@@ -273,6 +273,8 @@
   // random data even when using sandboxing mechanisms such as chroots,
   // Capsicum, etc.
 # define _LIBCPP_USING_ARC4_RANDOM
+#elif defined(__Fuchsia__)
+# define _LIBCPP_USING_GETENTROPY
 #elif defined(__native_client__)
   // NaCl's sandbox (which PNaCl also runs in) doesn't allow filesystem access,
   // including accesses to the special files under /dev. C++11's

Modified: libcxx/trunk/src/random.cpp
URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/random.cpp?rev=319523&r1=319522&r2=319523&view=diff
==============================================================================
--- libcxx/trunk/src/random.cpp (original)
+++ libcxx/trunk/src/random.cpp Thu Nov 30 22:34:33 2017
@@ -25,7 +25,9 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#if defined(_LIBCPP_USING_DEV_RANDOM)
+#if defined(_LIBCPP_USING_GETENTROPY)
+#include <sys/random.h>
+#elif defined(_LIBCPP_USING_DEV_RANDOM)
 #include <fcntl.h>
 #include <unistd.h>
 #elif defined(_LIBCPP_USING_NACL_RANDOM)
@@ -35,7 +37,30 @@
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-#if defined(_LIBCPP_USING_ARC4_RANDOM)
+#if defined(_LIBCPP_USING_GETENTROPY)
+
+random_device::random_device(const string& __token)
+{
+    if (__token != "/dev/urandom")
+        __throw_system_error(ENOENT, ("random device not supported " + __token).c_str());
+}
+
+random_device::~random_device()
+{
+}
+
+unsigned
+random_device::operator()()
+{
+    unsigned r;
+    size_t n = sizeof(r);
+    int err = getentropy(&r, n);
+    if (err)
+        __throw_system_error(errno, "random_device getentropy failed");
+    return r;
+}
+
+#elif defined(_LIBCPP_USING_ARC4_RANDOM)
 
 random_device::random_device(const string& __token)
 {




More information about the cfe-commits mailing list