Fix fibers gdb utils script
[folly.git] / folly / Random.cpp
index ef2e8b9cc5d6bc570870614398d1e31111246cee..d4fb39b4ea3a4eaaa1d9140dfe422bcdd610a090 100644 (file)
@@ -17,8 +17,6 @@
 #include <folly/Random.h>
 
 #include <atomic>
-#include <unistd.h>
-#include <sys/time.h>
 #include <mutex>
 #include <random>
 #include <array>
@@ -28,6 +26,8 @@
 #include <folly/File.h>
 #include <folly/FileUtil.h>
 #include <folly/ThreadLocal.h>
+#include <folly/portability/SysTime.h>
+#include <folly/portability/Unistd.h>
 
 #ifdef _MSC_VER
 # include <wincrypt.h>
@@ -42,8 +42,21 @@ void readRandomDevice(void* data, size_t size) {
   static folly::once_flag flag;
   static HCRYPTPROV cryptoProv;
   folly::call_once(flag, [&] {
-    PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
-                               PROV_RSA_FULL, 0));
+    if (!CryptAcquireContext(
+            &cryptoProv,
+            nullptr,
+            nullptr,
+            PROV_RSA_FULL,
+            CRYPT_VERIFYCONTEXT)) {
+      if (GetLastError() == NTE_BAD_KEYSET) {
+        // Mostly likely cause of this is that no key container
+        // exists yet, so try to create one.
+        PCHECK(CryptAcquireContext(
+            &cryptoProv, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET));
+      } else {
+        LOG(FATAL) << "Failed to acquire the default crypto context.";
+      }
+    }
   });
   CHECK(size <= std::numeric_limits<DWORD>::max());
   PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));