1 //===-- RandomNumberGenerator.cpp - Implement RNG class -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements deterministic random number generation (RNG).
10 // The current implementation is NOT cryptographically secure as it uses
11 // the C++11 <random> facilities.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/RandomNumberGenerator.h"
17 #include "DebugOptions.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/Windows/WindowsSupport.h"
25 #include "Unix/Unix.h"
30 #define DEBUG_TYPE "rng"
34 return new cl::opt
<uint64_t>(
35 "rng-seed", cl::value_desc("seed"), cl::Hidden
,
36 cl::desc("Seed for the random number generator"), cl::init(0));
40 static ManagedStatic
<cl::opt
<uint64_t>, CreateSeed
> Seed
;
41 void llvm::initRandomSeedOptions() { *Seed
; }
43 RandomNumberGenerator::RandomNumberGenerator(StringRef Salt
) {
44 LLVM_DEBUG(if (*Seed
== 0) dbgs()
45 << "Warning! Using unseeded random number generator.\n");
47 // Combine seed and salts using std::seed_seq.
48 // Data: Seed-low, Seed-high, Salt
49 // Note: std::seed_seq can only store 32-bit values, even though we
50 // are using a 64-bit RNG. This isn't a problem since the Mersenne
51 // twister constructor copies these correctly into its initial state.
52 std::vector
<uint32_t> Data
;
53 Data
.resize(2 + Salt
.size());
55 Data
[1] = *Seed
>> 32;
57 llvm::copy(Salt
, Data
.begin() + 2);
59 std::seed_seq
SeedSeq(Data
.begin(), Data
.end());
60 Generator
.seed(SeedSeq
);
63 RandomNumberGenerator::result_type
RandomNumberGenerator::operator()() {
67 // Get random vector of specified size
68 std::error_code
llvm::getRandomBytes(void *Buffer
, size_t Size
) {
71 if (CryptAcquireContext(&hProvider
, 0, 0, PROV_RSA_FULL
,
72 CRYPT_VERIFYCONTEXT
| CRYPT_SILENT
)) {
73 ScopedCryptContext
ScopedHandle(hProvider
);
74 if (CryptGenRandom(hProvider
, Size
, static_cast<BYTE
*>(Buffer
)))
75 return std::error_code();
77 return std::error_code(GetLastError(), std::system_category());
79 int Fd
= open("/dev/urandom", O_RDONLY
);
82 ssize_t BytesRead
= read(Fd
, Buffer
, Size
);
84 Ret
= std::error_code(errno
, std::system_category());
85 else if (BytesRead
!= static_cast<ssize_t
>(Size
))
86 Ret
= std::error_code(EIO
, std::system_category());
88 Ret
= std::error_code(errno
, std::system_category());
92 return std::error_code(errno
, std::system_category());