[libcxx] r210060 - [libc++] random_device fails if open returns zero

David Majnemer david.majnemer at gmail.com
Mon Jun 2 19:21:37 PDT 2014


Author: majnemer
Date: Mon Jun  2 21:21:37 2014
New Revision: 210060

URL: http://llvm.org/viewvc/llvm-project?rev=210060&view=rev
Log:
[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.

Modified:
    libcxx/trunk/src/random.cpp
    libcxx/trunk/test/numerics/rand/rand.device/ctor.pass.cpp

Modified: libcxx/trunk/src/random.cpp
URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/random.cpp?rev=210060&r1=210059&r2=210060&view=diff
==============================================================================
--- libcxx/trunk/src/random.cpp (original)
+++ libcxx/trunk/src/random.cpp Mon Jun  2 21:21:37 2014
@@ -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());
 }
 

Modified: libcxx/trunk/test/numerics/rand/rand.device/ctor.pass.cpp
URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/numerics/rand/rand.device/ctor.pass.cpp?rev=210060&r1=210059&r2=210060&view=diff
==============================================================================
--- libcxx/trunk/test/numerics/rand/rand.device/ctor.pass.cpp (original)
+++ libcxx/trunk/test/numerics/rand/rand.device/ctor.pass.cpp Mon Jun  2 21:21:37 2014
@@ -15,6 +15,7 @@
 
 #include <random>
 #include <cassert>
+#include <unistd.h>
 
 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");;
     }
     {





More information about the cfe-commits mailing list