LLVM: lib/Support/RandomNumberGenerator.cpp Source File (original) (raw)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

16

18

24#ifdef _WIN32

26#else

28#endif

29

30using namespace llvm;

31

32#define DEBUG_TYPE "rng"

33namespace {

34struct CreateSeed {

35 static void *call() {

38 cl::desc("Seed for the random number generator"), cl::init(0));

39 }

40};

41}

44

45RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {

47 << "Warning! Using unseeded random number generator.\n");

48

49

50

51

52

53

54 std::vector<uint32_t> Data;

58

60

61 std::seed_seq SeedSeq(Data.begin(), Data.end());

62 Generator.seed(SeedSeq);

63}

64

66 return Generator();

67}

68

69

71#ifdef _WIN32

72 HCRYPTPROV hProvider;

73 if (CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL,

74 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {

76 if (CryptGenRandom(hProvider, Size, static_cast<BYTE *>(Buffer)))

77 return std::error_code();

78 }

79 return std::error_code(GetLastError(), std::system_category());

80#else

81 int Fd = open("/dev/urandom", O_RDONLY);

82 if (Fd != -1) {

83 std::error_code Ret;

84 ssize_t BytesRead = read(Fd, Buffer, Size);

85 if (BytesRead == -1)

87 else if (BytesRead != static_cast<ssize_t>(Size))

88 Ret = std::error_code(EIO, std::system_category());

89 if (close(Fd) == -1)

91

92 return Ret;

93 }

95#endif

96}

static ManagedStatic< cl::opt< uint64_t >, CreateSeed > Seed

Definition RandomNumberGenerator.cpp:42

ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...

generator_type::result_type result_type

LLVM_ABI result_type operator()()

Returns a random number in the range [0, Max).

Definition RandomNumberGenerator.cpp:65

StringRef - Represent a constant reference to a string, i.e.

constexpr size_t size() const

size - Get the string size.

initializer< Ty > init(const Ty &Val)

This is an optimization pass for GlobalISel generic memory operations.

ScopedHandle< CryptContextTraits > ScopedCryptContext

LLVM_ABI raw_ostream & dbgs()

dbgs() - This returns a reference to a raw_ostream for debugging messages.

FunctionAddr VTableAddr uintptr_t uintptr_t Data

void initRandomSeedOptions()

Definition RandomNumberGenerator.cpp:43

LLVM_ABI std::error_code getRandomBytes(void *Buffer, size_t Size)

Definition RandomNumberGenerator.cpp:70

OutputIt copy(R &&Range, OutputIt Out)

std::error_code errnoAsErrorCode()

Helper to get errno as an std::error_code.