Botan 3.14.1
Crypto and TLS for C&
hwrng_x86.cpp
Go to the documentation of this file.
1/*
2* (C) 2016,2019,2020,2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/internal/hwrng.h>
8
9#include <botan/internal/isa_extn.h>
10#include <botan/internal/target_info.h>
11
12#if !defined(BOTAN_USE_GCC_INLINE_ASM)
13 #include <immintrin.h>
14#endif
15
16namespace Botan::HWRNG {
17
18namespace {
19
20#if defined(BOTAN_TARGET_ARCH_IS_X86_32)
21using rdrand_output = uint32_t;
22#else
23using rdrand_output = uint64_t;
24#endif
25
26BOTAN_FN_ISA_RNG std::optional<rdrand_output> rdrand() {
27 rdrand_output output = 0; // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
28 int cf = 0; // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
29
30#if defined(BOTAN_USE_GCC_INLINE_ASM)
31 // same asm seq works for 32 and 64 bit
32 // NOLINTNEXTLINE(*-no-assembler)
33 asm volatile("rdrand %0; adcl $0,%1" : "=r"(output), "=r"(cf) : "0"(output), "1"(cf) : "cc");
34#elif defined(BOTAN_TARGET_ARCH_IS_X86_32)
35 cf = _rdrand32_step(&output);
36#else
37 unsigned long long outputll = 0;
38 cf = _rdrand64_step(&outputll);
39 output = static_cast<uint64_t>(outputll);
40#endif
41
42 if(cf == 1) {
43 return output;
44 } else {
45 return std::nullopt;
46 }
47}
48
49} // namespace
50
53}
54
55std::optional<uint64_t> read_once() {
56#if defined(BOTAN_TARGET_ARCH_IS_X86_32)
57 // In 32-bit mode RDRAND can only produce 32 bits per invocation
58 const auto lo = rdrand();
59 const auto hi = rdrand();
60
61 if(lo && hi) {
62 return (static_cast<uint64_t>(*hi) << 32) | *lo;
63 } else {
64 return std::nullopt;
65 }
66#else
67 return rdrand();
68#endif
69}
70
71} // namespace Botan::HWRNG
CPUFeature Feature
Definition cpuid.h:44
std::optional< uint64_t > read_once()
CPUID::Feature feature()