1 //===-------------------------- random.cpp --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #if defined(_LIBCPP_USING_WIN32_RANDOM)
13 // Must be defined before including stdlib.h to enable rand_s().
15 #endif // defined(_LIBCPP_USING_WIN32_RANDOM)
18 #include "system_error"
21 #define rename solaris_headers_are_broken
22 #endif // defined(__sun__)
28 #if defined(_LIBCPP_USING_DEV_RANDOM)
31 #elif defined(_LIBCPP_USING_NACL_RANDOM)
32 #include <nacl/nacl_random.h>
36 _LIBCPP_BEGIN_NAMESPACE_STD
38 #if defined(_LIBCPP_USING_ARC4_RANDOM)
40 random_device::random_device(const string& __token)
42 if (__token != "/dev/urandom")
43 __throw_system_error(ENOENT, ("random device not supported " + __token).c_str());
46 random_device::~random_device()
51 random_device::operator()()
56 #elif defined(_LIBCPP_USING_DEV_RANDOM)
58 random_device::random_device(const string& __token)
59 : __f_(open(__token.c_str(), O_RDONLY))
62 __throw_system_error(errno, ("random_device failed to open " + __token).c_str());
65 random_device::~random_device()
71 random_device::operator()()
75 char* p = reinterpret_cast<char*>(&r);
78 ssize_t s = read(__f_, p, n);
80 __throw_system_error(ENODATA, "random_device got EOF");
84 __throw_system_error(errno, "random_device got an unexpected error");
87 n -= static_cast<size_t>(s);
88 p += static_cast<size_t>(s);
93 #elif defined(_LIBCPP_USING_NACL_RANDOM)
95 random_device::random_device(const string& __token)
97 if (__token != "/dev/urandom")
98 __throw_system_error(ENOENT, ("random device not supported " + __token).c_str());
99 int error = nacl_secure_random_init();
101 __throw_system_error(error, ("random device failed to open " + __token).c_str());
104 random_device::~random_device()
109 random_device::operator()()
112 size_t n = sizeof(r);
113 size_t bytes_written;
114 int error = nacl_secure_random(&r, n, &bytes_written);
116 __throw_system_error(error, "random_device failed getting bytes");
117 else if (bytes_written != n)
118 __throw_runtime_error("random_device failed to obtain enough bytes");
122 #elif defined(_LIBCPP_USING_WIN32_RANDOM)
124 random_device::random_device(const string& __token)
126 if (__token != "/dev/urandom")
127 __throw_system_error(ENOENT, ("random device not supported " + __token).c_str());
130 random_device::~random_device()
135 random_device::operator()()
138 errno_t err = rand_s(&r);
140 __throw_system_error(err, "random_device rand_s failed.");
145 #error "Random device not implemented for this architecture"
149 random_device::entropy() const _NOEXCEPT
154 _LIBCPP_END_NAMESPACE_STD