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 //===----------------------------------------------------------------------===//
10 #if defined(_LIBCPP_USING_WIN32_RANDOM)
11 // Must be defined before including stdlib.h to enable rand_s().
13 #endif // defined(_LIBCPP_USING_WIN32_RANDOM)
16 #include "system_error"
19 #define rename solaris_headers_are_broken
20 #endif // defined(__sun__)
26 #if defined(_LIBCPP_USING_DEV_RANDOM)
29 #elif defined(_LIBCPP_USING_NACL_RANDOM)
30 #include <nacl/nacl_random.h>
34 _LIBCPP_BEGIN_NAMESPACE_STD
36 #if defined(_LIBCPP_USING_ARC4_RANDOM)
38 random_device::random_device(const string
& __token
)
40 if (__token
!= "/dev/urandom")
41 __throw_system_error(ENOENT
, ("random device not supported " + __token
).c_str());
44 random_device::~random_device()
49 random_device::operator()()
54 #elif defined(_LIBCPP_USING_DEV_RANDOM)
56 random_device::random_device(const string
& __token
)
57 : __f_(open(__token
.c_str(), O_RDONLY
))
60 __throw_system_error(errno
, ("random_device failed to open " + __token
).c_str());
63 random_device::~random_device()
69 random_device::operator()()
73 char* p
= reinterpret_cast<char*>(&r
);
76 ssize_t s
= read(__f_
, p
, n
);
78 __throw_system_error(ENODATA
, "random_device got EOF");
82 __throw_system_error(errno
, "random_device got an unexpected error");
85 n
-= static_cast<size_t>(s
);
86 p
+= static_cast<size_t>(s
);
91 #elif defined(_LIBCPP_USING_NACL_RANDOM)
93 random_device::random_device(const string
& __token
)
95 if (__token
!= "/dev/urandom")
96 __throw_system_error(ENOENT
, ("random device not supported " + __token
).c_str());
97 int error
= nacl_secure_random_init();
99 __throw_system_error(error
, ("random device failed to open " + __token
).c_str());
102 random_device::~random_device()
107 random_device::operator()()
110 size_t n
= sizeof(r
);
111 size_t bytes_written
;
112 int error
= nacl_secure_random(&r
, n
, &bytes_written
);
114 __throw_system_error(error
, "random_device failed getting bytes");
115 else if (bytes_written
!= n
)
116 __throw_runtime_error("random_device failed to obtain enough bytes");
120 #elif defined(_LIBCPP_USING_WIN32_RANDOM)
122 random_device::random_device(const string
& __token
)
124 if (__token
!= "/dev/urandom")
125 __throw_system_error(ENOENT
, ("random device not supported " + __token
).c_str());
128 random_device::~random_device()
133 random_device::operator()()
136 errno_t err
= rand_s(&r
);
138 __throw_system_error(err
, "random_device rand_s failed.");
143 #error "Random device not implemented for this architecture"
147 random_device::entropy() const _NOEXCEPT
152 _LIBCPP_END_NAMESPACE_STD