[libcxx-commits] [PATCH] D94953: [libc++] Use ioctl when available to get random_device entropy.
Marek Kurdej via Phabricator via libcxx-commits
libcxx-commits at lists.llvm.org
Tue Jan 19 01:01:43 PST 2021
curdeius created this revision.
curdeius added a reviewer: ldionne.
curdeius requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.
Repository:
rG LLVM Github Monorepo
https://reviews.llvm.org/D94953
Files:
libcxx/src/random.cpp
libcxx/test/std/numerics/rand/rand.device/entropy.pass.cpp
Index: libcxx/test/std/numerics/rand/rand.device/entropy.pass.cpp
===================================================================
--- libcxx/test/std/numerics/rand/rand.device/entropy.pass.cpp
+++ libcxx/test/std/numerics/rand/rand.device/entropy.pass.cpp
@@ -19,11 +19,11 @@
#include "test_macros.h"
-int main(int, char**)
-{
- std::random_device r;
- double e = r.entropy();
- ((void)e); // Prevent unused warning
+int main(int, char**) {
+ std::random_device r;
+ double e = r.entropy();
+ assert(e >= 0);
+ assert(e <= 32);
return 0;
}
Index: libcxx/src/random.cpp
===================================================================
--- libcxx/src/random.cpp
+++ libcxx/src/random.cpp
@@ -13,6 +13,7 @@
#define _CRT_RAND_S
#endif // defined(_LIBCPP_USING_WIN32_RANDOM)
+#include "limits"
#include "random"
#include "system_error"
@@ -29,6 +30,10 @@
#elif defined(_LIBCPP_USING_DEV_RANDOM)
#include <fcntl.h>
#include <unistd.h>
+#if __has_include(<unistd.h>) && __has_include(<linux/random.h>)
+#include <sys/ioctl.h>
+#include <linux/random.h>
+#endif
#elif defined(_LIBCPP_USING_NACL_RANDOM)
#include <nacl/nacl_random.h>
#endif
@@ -172,7 +177,21 @@
double
random_device::entropy() const _NOEXCEPT
{
+#if defined(_LIBCPP_USING_DEV_RANDOM) && defined(RNDGETENTCNT)
+ int ent;
+ if (::ioctl(__f_, RNDGETENTCNT, &ent) < 0)
+ return 0;
+
+ if (ent < 0)
return 0;
+
+ if (ent > std::numeric_limits<unsigned int>::digits)
+ return std::numeric_limits<unsigned int>::digits;
+
+ return ent;
+#else
+ return 0;
+#endif
}
_LIBCPP_END_NAMESPACE_STD
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D94953.317479.patch
Type: text/x-patch
Size: 1611 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20210119/92276fc0/attachment-0001.bin>
More information about the libcxx-commits
mailing list