Remove memory leak from readRandomDevice by using a raw fd
authorBrian Watling <bwatling@fb.com>
Wed, 5 Nov 2014 23:17:10 +0000 (15:17 -0800)
committerPavlo Kushnir <pavlo@fb.com>
Sat, 8 Nov 2014 02:38:18 +0000 (18:38 -0800)
Summary: Switch from dynamically allocating a File to using a raw fd for readRandomDevice. This prevents races at shutdown while also eliminating the memory leak

Test Plan: run unit tests

Reviewed By: meyering@fb.com

Subscribers: njormrod, folly-diffs@, tao-eng@

FB internal diff: D1662151

Signature: t1:1662151:1415229242:525b6294b27bb68b5dda70aadb8d3ba1cc61b815

folly/Random.cpp

index 4ed578c31dd8266588ed30b155a6512b7eb27c57..fcebfde9f208ba8df0a0c5eaf6d18bea4b97ae5f 100644 (file)
@@ -31,10 +31,10 @@ namespace folly {
 namespace {
 
 void readRandomDevice(void* data, size_t size) {
-  // 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);
+  // Keep the random device open for the duration of the program.
+  static int randomFd = ::open("/dev/urandom", O_RDONLY);
+  PCHECK(randomFd >= 0);
+  auto bytesRead = readFull(randomFd, data, size);
   PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
 }