1 //===----------------------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // <random>
11 
12 // class random_device;
13 
14 // explicit random_device(const string& token = implementation-defined);
15 
16 // For the following ctors, the standard states: "The semantics and default
17 // value of the token parameter are implementation-defined". Implementations
18 // therefore aren't required to accept any string, but the default shouldn't
19 // throw.
20 
21 #include <random>
22 #include <system_error>
23 #include <cassert>
24 
25 #if !defined(_WIN32)
26 #include <unistd.h>
27 #endif
28 
29 #include "test_macros.h"
30 
31 
32 bool is_valid_random_device(const std::string &token) {
33 #if defined(_LIBCPP_USING_DEV_RANDOM)
34   // Not an exhaustive list: they're the only tokens that are tested below.
35   return token == "/dev/urandom" || token == "/dev/random";
36 #else
37   return token == "/dev/urandom";
38 #endif
39 }
40 
41 void check_random_device_valid(const std::string &token) {
42   std::random_device r(token);
43 }
44 
45 void check_random_device_invalid(const std::string &token) {
46 #ifndef TEST_HAS_NO_EXCEPTIONS
47   try {
48     std::random_device r(token);
49     LIBCPP_ASSERT(false);
50   } catch (const std::system_error&) {
51   }
52 #endif
53 }
54 
55 
56 int main() {
57   {
58     std::random_device r;
59   }
60   {
61     std::string token = "wrong file";
62     check_random_device_invalid(token);
63   }
64   {
65     std::string token = "/dev/urandom";
66     if (is_valid_random_device(token))
67       check_random_device_valid(token);
68     else
69       check_random_device_invalid(token);
70   }
71   {
72     std::string token = "/dev/random";
73     if (is_valid_random_device(token))
74       check_random_device_valid(token);
75     else
76       check_random_device_invalid(token);
77   }
78 #if !defined(_WIN32)
79 // Test that random_device(const string&) properly handles getting
80 // a file descriptor with the value '0'. Do this by closing the standard
81 // streams so that the descriptor '0' is available.
82   {
83     int ec;
84     ec = close(STDIN_FILENO);
85     assert(!ec);
86     ec = close(STDOUT_FILENO);
87     assert(!ec);
88     ec = close(STDERR_FILENO);
89     assert(!ec);
90     std::random_device r;
91   }
92 #endif // !defined(_WIN32)
93 }
94