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 //===----------------------------------------------------------------------===//
11 // Must be defined before including stdlib.h to enable rand_s().
14 #endif // defined(_WIN32)
17 #include "system_error"
20 #define rename solaris_headers_are_broken
21 #endif // defined(__sun__)
25 #endif // !defined(_WIN32)
27 #if defined(_LIBCPP_USING_NACL_RANDOM)
28 #include <nacl/nacl_random.h>
29 #endif // defined(_LIBCPP_USING_NACL_RANDOM)
31 _LIBCPP_BEGIN_NAMESPACE_STD
35 random_device::random_device(const string&)
39 random_device::~random_device()
44 random_device::operator()()
47 errno_t err = rand_s(&r);
49 __throw_system_error(err, "random_device rand_s failed.");
53 #elif defined(_LIBCPP_USING_NACL_RANDOM)
55 random_device::random_device(const string& __token)
57 if (__token != "/dev/urandom")
58 __throw_system_error(ENOENT, ("random device not supported " + __token).c_str());
59 int error = nacl_secure_random_init();
61 __throw_system_error(error, ("random device failed to open " + __token).c_str());
64 random_device::~random_device()
69 random_device::operator()()
73 char* p = reinterpret_cast<char*>(&r);
75 int error = nacl_secure_random(&r, n, &bytes_written);
77 __throw_system_error(error, "random_device failed getting bytes");
78 else if (bytes_written != n)
79 __throw_runtime_error("random_device failed to obtain enough bytes");
83 #else // !defined(_WIN32) && !defined(_LIBCPP_USING_NACL_RANDOM)
85 random_device::random_device(const string& __token)
86 : __f_(open(__token.c_str(), O_RDONLY))
89 __throw_system_error(errno, ("random_device failed to open " + __token).c_str());
92 random_device::~random_device()
98 random_device::operator()()
101 size_t n = sizeof(r);
102 char* p = reinterpret_cast<char*>(&r);
105 ssize_t s = read(__f_, p, n);
107 __throw_system_error(ENODATA, "random_device got EOF");
111 __throw_system_error(errno, "random_device got an unexpected error");
114 n -= static_cast<size_t>(s);
115 p += static_cast<size_t>(s);
120 #endif // defined(_WIN32) || defined(_LIBCPP_USING_NACL_RANDOM)
123 random_device::entropy() const _NOEXCEPT
128 _LIBCPP_END_NAMESPACE_STD