[llvm-commits] [llvm] r156414 - /llvm/trunk/lib/Support/Unix/Process.inc
Daniel Dunbar
daniel at zuster.org
Tue May 8 13:38:00 PDT 2012
Author: ddunbar
Date: Tue May 8 15:38:00 2012
New Revision: 156414
URL: http://llvm.org/viewvc/llvm-project?rev=156414&view=rev
Log:
[Support] Fix sys::GetRandomNumber() to always use a high quality seed.
Modified:
llvm/trunk/lib/Support/Unix/Process.inc
Modified: llvm/trunk/lib/Support/Unix/Process.inc
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/Unix/Process.inc?rev=156414&r1=156413&r2=156414&view=diff
==============================================================================
--- llvm/trunk/lib/Support/Unix/Process.inc (original)
+++ llvm/trunk/lib/Support/Unix/Process.inc Tue May 8 15:38:00 2012
@@ -12,6 +12,8 @@
//===----------------------------------------------------------------------===//
#include "Unix.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/Support/TimeValue.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
@@ -300,13 +302,21 @@
#if !defined(HAVE_ARC4RANDOM)
static unsigned GetRandomNumberSeed() {
- unsigned seed = ::time(NULL); // FIXME: It might not provide unique seed.
- FILE *RandomSource = ::fopen("/dev/urandom", "r");
- if (RandomSource) {
- ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
+ // Attempt to get the initial seed from /dev/urandom, if possible.
+ if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
+ unsigned seed;
+ int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
::fclose(RandomSource);
+
+ // Return the seed if the read was successful.
+ if (count == 1)
+ return seed;
}
- return seed;
+
+ // Otherwise, swizzle the current time and the process ID to form a reasonable
+ // seed.
+ TimeValue Now = llvm::TimeValue::now();
+ return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
}
#endif
More information about the llvm-commits
mailing list