xref: /freebsd/contrib/llvm-project/llvm/lib/Support/RandomNumberGenerator.cpp (revision e32fecd0c2c3ee37c47ee100f169e7eb0282a873)
1 //===-- RandomNumberGenerator.cpp - Implement RNG class -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Support/RandomNumberGenerator.h"
16 
17 #include "DebugOptions.h"
18 
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #ifdef _WIN32
23 #include "llvm/Support/Windows/WindowsSupport.h"
24 #else
25 #include "Unix/Unix.h"
26 #endif
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "rng"
31 namespace {
32 struct CreateSeed {
33   static void *call() {
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));
37   }
38 };
39 } // namespace
40 static ManagedStatic<cl::opt<uint64_t>, CreateSeed> Seed;
41 void llvm::initRandomSeedOptions() { *Seed; }
42 
43 RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {
44   LLVM_DEBUG(if (*Seed == 0) dbgs()
45              << "Warning! Using unseeded random number generator.\n");
46 
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());
54   Data[0] = *Seed;
55   Data[1] = *Seed >> 32;
56 
57   llvm::copy(Salt, Data.begin() + 2);
58 
59   std::seed_seq SeedSeq(Data.begin(), Data.end());
60   Generator.seed(SeedSeq);
61 }
62 
63 RandomNumberGenerator::result_type RandomNumberGenerator::operator()() {
64   return Generator();
65 }
66 
67 // Get random vector of specified size
68 std::error_code llvm::getRandomBytes(void *Buffer, size_t Size) {
69 #ifdef _WIN32
70   HCRYPTPROV hProvider;
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();
76   }
77   return std::error_code(GetLastError(), std::system_category());
78 #else
79   int Fd = open("/dev/urandom", O_RDONLY);
80   if (Fd != -1) {
81     std::error_code Ret;
82     ssize_t BytesRead = read(Fd, Buffer, Size);
83     if (BytesRead == -1)
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());
87     if (close(Fd) == -1)
88       Ret = std::error_code(errno, std::system_category());
89 
90     return Ret;
91   }
92   return std::error_code(errno, std::system_category());
93 #endif
94 }
95