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 <cassert>
23 #include <unistd.h>
24 
is_valid_random_device(const std::string & token)25 bool is_valid_random_device(const std::string &token) {
26 #if defined(_LIBCPP_USING_DEV_RANDOM)
27   // Not an exhaustive list: they're the only tokens that are tested below.
28   return token == "/dev/urandom" || token == "/dev/random";
29 #else
30   return token == "/dev/urandom";
31 #endif
32 }
33 
check_random_device_valid(const std::string & token)34 void check_random_device_valid(const std::string &token) {
35   std::random_device r(token);
36 }
37 
check_random_device_invalid(const std::string & token)38 void check_random_device_invalid(const std::string &token) {
39   try {
40     std::random_device r(token);
41     assert(false);
42   } catch (const std::system_error &e) {
43   }
44 }
45 
main()46 int main() {
47   { std::random_device r; }
48 
49   {
50     int ec;
51     ec = close(STDIN_FILENO);
52     assert(!ec);
53     ec = close(STDOUT_FILENO);
54     assert(!ec);
55     ec = close(STDERR_FILENO);
56     assert(!ec);
57     std::random_device r;
58   }
59 
60   {
61     std::string token = "wrong file";
62     if (is_valid_random_device(token))
63       check_random_device_valid(token);
64     else
65       check_random_device_invalid(token);
66   }
67 
68   {
69     std::string token = "/dev/urandom";
70     if (is_valid_random_device(token))
71       check_random_device_valid(token);
72     else
73       check_random_device_invalid(token);
74   }
75 
76   {
77     std::string token = "/dev/random";
78     if (is_valid_random_device(token))
79       check_random_device_valid(token);
80     else
81       check_random_device_invalid(token);
82   }
83 }
84