https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100444

--- Comment #8 from Jonathan Wakely <redi at gcc dot gnu.org> ---
g:b0c0d878a8b5bf39dbea4c192fed26d340524439 enabled RDRAND and RDSEED for AMD
chips, where previously we'd only used RDRAND and only for Intel (which caused
one particular idiot to complain that we "hate AMD"). I think we originally
didn't do it for AMD because of an older (but similar) bug:
https://bugzilla.kernel.org/show_bug.cgi?id=85911

N.B. If you know you have a broken chip and can change the source you can
select a different source, e.g. std::random_device rd("/dev/urandom").


I think this should work:

--- a/libstdc++-v3/src/c++11/random.cc
+++ b/libstdc++-v3/src/c++11/random.cc
@@ -101,6 +101,19 @@ namespace std _GLIBCXX_VISIBILITY(default)

       return val;
     }
+
+    bool
+    __attribute__ ((target("rdrnd")))
+    __x86_rdrand_is_usable()
+    {
+      for (int borkcount = 0; borkcount < 10; ++borkcount)
+       {
+         // AMD Ryzen 3000 bug, see PR libstdc++/100444
+         if (__x86_rdrand(nullptr) != 0xffffffff)
+           return true;
+       }
+      return false;
+    }
 #endif

 #if USE_RDSEED
@@ -271,7 +284,7 @@ namespace std _GLIBCXX_VISIBILITY(default)
 #ifdef USE_RDRAND
              // CPUID.01H:ECX.RDRAND[bit 30]
              __cpuid(1, eax, ebx, ecx, edx);
-             if (ecx & bit_RDRND)
+             if (ecx & bit_RDRND && __x86_rdrand_is_usable())
                {
                  _M_func = &__x86_rdseed_rdrand;
                  return;
@@ -297,8 +310,13 @@ namespace std _GLIBCXX_VISIBILITY(default)
          __cpuid(1, eax, ebx, ecx, edx);
          if (ecx & bit_RDRND)
            {
-             _M_func = &__x86_rdrand;
-             return;
+             if (__x86_rdrand_is_usable())
+               {
+                 _M_func = &__x86_rdrand;
+                 return;
+               }
+             else if (which == rdrand)
+               __throw_runtime_error(__N("random_device: RDRAND is buggy"));
            }
        }
     }

If you ask for "rdrand" specifically you'll get an exception telling you it's
buggy. If you just let the library choose for you, then it will skip rdrand and
pick the next alternative, which will be "/dev/urandom" for most systems.

Reply via email to