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