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/Error.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/Windows/WindowsSupport.h"
27 #include "Unix/Unix.h"
32 #define DEBUG_TYPE "rng"
36 return new cl::opt
<uint64_t>(
37 "rng-seed", cl::value_desc("seed"), cl::Hidden
,
38 cl::desc("Seed for the random number generator"), cl::init(0));
42 static ManagedStatic
<cl::opt
<uint64_t>, CreateSeed
> Seed
;
43 void llvm::initRandomSeedOptions() { *Seed
; }
45 RandomNumberGenerator::RandomNumberGenerator(StringRef Salt
) {
46 LLVM_DEBUG(if (*Seed
== 0) dbgs()
47 << "Warning! Using unseeded random number generator.\n");
49 // Combine seed and salts using std::seed_seq.
50 // Data: Seed-low, Seed-high, Salt
51 // Note: std::seed_seq can only store 32-bit values, even though we
52 // are using a 64-bit RNG. This isn't a problem since the Mersenne
53 // twister constructor copies these correctly into its initial state.
54 std::vector
<uint32_t> Data
;
55 Data
.resize(2 + Salt
.size());
57 Data
[1] = *Seed
>> 32;
59 llvm::copy(Salt
, Data
.begin() + 2);
61 std::seed_seq
SeedSeq(Data
.begin(), Data
.end());
62 Generator
.seed(SeedSeq
);
65 RandomNumberGenerator::result_type
RandomNumberGenerator::operator()() {
69 // Get random vector of specified size
70 std::error_code
llvm::getRandomBytes(void *Buffer
, size_t Size
) {
73 if (CryptAcquireContext(&hProvider
, 0, 0, PROV_RSA_FULL
,
74 CRYPT_VERIFYCONTEXT
| CRYPT_SILENT
)) {
75 ScopedCryptContext
ScopedHandle(hProvider
);
76 if (CryptGenRandom(hProvider
, Size
, static_cast<BYTE
*>(Buffer
)))
77 return std::error_code();
79 return std::error_code(GetLastError(), std::system_category());
81 int Fd
= open("/dev/urandom", O_RDONLY
);
84 ssize_t BytesRead
= read(Fd
, Buffer
, Size
);
86 Ret
= errnoAsErrorCode();
87 else if (BytesRead
!= static_cast<ssize_t
>(Size
))
88 Ret
= std::error_code(EIO
, std::system_category());
90 Ret
= errnoAsErrorCode();
94 return errnoAsErrorCode();