From 1e9592a9c71ed87c806946ad2cccc1bcb472324d Mon Sep 17 00:00:00 2001 From: David Majnemer Date: Tue, 3 Jun 2014 02:21:37 +0000 Subject: [PATCH] [libc++] random_device fails if open returns zero random_device::random_device(const string&) wrongly assumes that open can only validly return a file descriptor greater than zero. This results in random_device believing that it didn't successfully open the device causing it to throw in it's constructor, this ends up leaking a file descriptor. The fix is simple, don't error on file descriptors which are zero. llvm-svn: 210060 --- libcxx/src/random.cpp | 2 +- libcxx/test/numerics/rand/rand.device/ctor.pass.cpp | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/libcxx/src/random.cpp b/libcxx/src/random.cpp index bd24f2e..21e2168 100644 --- a/libcxx/src/random.cpp +++ b/libcxx/src/random.cpp @@ -49,7 +49,7 @@ random_device::operator()() random_device::random_device(const string& __token) : __f_(open(__token.c_str(), O_RDONLY)) { - if (__f_ <= 0) + if (__f_ < 0) __throw_system_error(errno, ("random_device failed to open " + __token).c_str()); } diff --git a/libcxx/test/numerics/rand/rand.device/ctor.pass.cpp b/libcxx/test/numerics/rand/rand.device/ctor.pass.cpp index a7c38d4..dfa546b 100644 --- a/libcxx/test/numerics/rand/rand.device/ctor.pass.cpp +++ b/libcxx/test/numerics/rand/rand.device/ctor.pass.cpp @@ -15,6 +15,7 @@ #include #include +#include int main() { @@ -30,6 +31,16 @@ int main() std::random_device r; } { + int ec; + ec = close(STDIN_FILENO); + assert(!ec); + ec = close(STDOUT_FILENO); + assert(!ec); + ec = close(STDERR_FILENO); + assert(!ec); + std::random_device r; + } + { std::random_device r("/dev/urandom");; } { -- 2.7.4