Fix crashes in readRandomDevice()
authorBrian Watling <bwatling@fb.com>
Wed, 5 Nov 2014 22:50:37 +0000 (14:50 -0800)
committerPavlo Kushnir <pavlo@fb.com>
Sat, 8 Nov 2014 02:37:56 +0000 (18:37 -0800)
Summary: The comment in readRandomDevice() lies - the PCHECK fails with "Bad file descriptor" in some tests. This is most likely due to a race where a background thread is calling readRandomDevice() while the main thread shuts down. Another possibility is bad destruction order, where rnadomDevice is destroyed before some other static object whose destructor calls readRandomDevice(). Either way, this fixes it without having to chace down every instance.

Test Plan: run unit tests

Reviewed By: meyering@fb.com

Subscribers: antonl, trunkagent, meyering, simpkins, njormrod, folly-diffs@, tao-eng@

FB internal diff: D1660903

Signature: t1:1660903:1415215895:7f1f96ab7416b45c4dc18e78173fb59eb27bd03b

folly/Random.cpp

index 533ac407a801dc06ea493b1bdfb64b8377d8c7bb..4ed578c31dd8266588ed30b155a6512b7eb27c57 100644 (file)
@@ -31,8 +31,9 @@ namespace folly {
 namespace {
 
 void readRandomDevice(void* data, size_t size) {
-  // Keep it open for the duration of the program
-  static File randomDevice("/dev/urandom");
+  // Keep it open for the duration of the program. Note that we leak the File
+  // to ensure the file is indeed open for the duration of the program.
+  static File& randomDevice = *new File("/dev/urandom");
   auto bytesRead = readFull(randomDevice.fd(), data, size);
   PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
 }