Debian Codegraph @

debian/rust-vendor/getrandom/src/backends/rdrand.rs

raw
1 //! RDRAND backend for x86(-64) targets
2 use crate::{Error, util::slice_as_uninit};
3 use core::mem::{MaybeUninit, size_of};
4
5 #[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
6 compile_error!("`rdrand` backend can be enabled only for x86 and x86-64 targets!");
7
8 cfg_if! {
9 if #[cfg(target_arch = "x86_64")] {
10 use core::arch::x86_64 as arch;
11 use arch::_rdrand64_step as rdrand_step;
12 type Word = u64;
13 } else if #[cfg(target_arch = "x86")] {
14 use core::arch::x86 as arch;
15 use arch::_rdrand32_step as rdrand_step;
16 type Word = u32;
17 }
18 }
19
20 // Recommendation from "Intel® Digital Random Number Generator (DRNG) Software
21 // Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures
22 // Software Developer’s Manual" - Volume 1 - Section 7.3.17.1.
23 const RETRY_LIMIT: usize = 10;
24
25 #[target_feature(enable = "rdrand")]
26 fn rdrand() -> Option<Word> {
27 for _ in 0..RETRY_LIMIT {
28 let mut val = 0;
29 // SAFETY: this function is safe to call from a `[target_feature(enable
30 // = "rdrand")]` context (it itself is annotated with
31 // `target_feature(enable = "rdrand")`) but was marked unsafe until
32 // https://github.com/rust-lang/stdarch/commit/59864cd which was pulled
33 // in via https://github.com/rust-lang/rust/commit/f2eb88b which is
34 // expected to be included in 1.93.0. Since our MSRV is 1.85, we need to
35 // use unsafe here and suppress the lint.
36 //
37 // TODO(MSRV 1.93): remove allow(unused_unsafe) and the unsafe block.
38 #[allow(unused_unsafe)]
39 if unsafe { rdrand_step(&mut val) } == 1 {
40 return Some(val);
41 }
42 }
43 None
44 }
45
46 // "rdrand" target feature requires "+rdrand" flag, see https://github.com/rust-lang/rust/issues/49653.
47 #[cfg(all(target_env = "sgx", not(target_feature = "rdrand")))]
48 compile_error!(
49 "SGX targets require 'rdrand' target feature. Enable by using -C target-feature=+rdrand."
50 );
51
52 // Run a small self-test to make sure we aren't repeating values
53 // Adapted from Linux's test in arch/x86/kernel/cpu/rdrand.c
54 // Fails with probability < 2^(-90) on 32-bit systems
55 #[target_feature(enable = "rdrand")]
56 fn self_test() -> bool {
57 // On AMD, RDRAND returns 0xFF...FF on failure, count it as a collision.
58 let mut prev = Word::MAX;
59 let mut fails = 0;
60 for _ in 0..8 {
61 match rdrand() {
62 Some(val) if val == prev => fails += 1,
63 Some(val) => prev = val,
64 None => return false,
65 };
66 }
67 fails <= 2
68 }
69
70 #[cold]
71 #[inline(never)]
72 fn init() -> bool {
73 #[cfg(not(target_feature = "rdrand"))]
74 {
75 // SAFETY: All Rust x86 targets are new enough to have CPUID, and we
76 // check that leaf 1 is supported before using it.
77 //
78 // TODO(MSRV 1.94): remove allow(unused_unsafe) and the unsafe blocks for `__cpuid`.
79 #[allow(unused_unsafe)]
80 let cpuid0 = unsafe { arch::__cpuid(0) };
81 if cpuid0.eax < 1 {
82 return false;
83 }
84 #[allow(unused_unsafe)]
85 let cpuid1 = unsafe { arch::__cpuid(1) };
86
87 let vendor_id = [
88 cpuid0.ebx.to_le_bytes(),
89 cpuid0.edx.to_le_bytes(),
90 cpuid0.ecx.to_le_bytes(),
91 ];
92 if vendor_id == [*b"Auth", *b"enti", *b"cAMD"] {
93 let mut family = (cpuid1.eax >> 8) & 0xF;
94 if family == 0xF {
95 family += (cpuid1.eax >> 20) & 0xFF;
96 }
97 // AMD CPUs families before 17h (Zen) sometimes fail to set CF when
98 // RDRAND fails after suspend. Don't use RDRAND on those families.
99 // See https://bugzilla.redhat.com/show_bug.cgi?id=1150286
100 if family < 0x17 {
101 return false;
102 }
103 }
104
105 const RDRAND_FLAG: u32 = 1 << 30;
106 if cpuid1.ecx & RDRAND_FLAG == 0 {
107 return false;
108 }
109 }
110
111 // SAFETY: We have already checked that rdrand is available.
112 unsafe { self_test() }
113 }
114
115 fn is_rdrand_good() -> bool {
116 #[path = "../utils/lazy_bool.rs"]
117 mod lazy;
118
119 static RDRAND_GOOD: lazy::LazyBool = lazy::LazyBool::new();
120
121 RDRAND_GOOD.unsync_init(init)
122 }
123
124 #[target_feature(enable = "rdrand")]
125 fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()> {
126 // We use chunks_exact_mut instead of chunks_mut as it allows almost all
127 // calls to memcpy to be elided by the compiler.
128 let mut chunks = dest.chunks_exact_mut(size_of::<Word>());
129 for chunk in chunks.by_ref() {
130 let src = rdrand()?.to_ne_bytes();
131 chunk.copy_from_slice(slice_as_uninit(&src));
132 }
133
134 let tail = chunks.into_remainder();
135 let n = tail.len();
136 if n > 0 {
137 let src = rdrand()?.to_ne_bytes();
138 tail.copy_from_slice(slice_as_uninit(&src[..n]));
139 }
140 Some(())
141 }
142
143 #[cfg(target_arch = "x86_64")]
144 #[target_feature(enable = "rdrand")]
145 fn rdrand_u32() -> Option<u32> {
146 rdrand().map(crate::util::truncate)
147 }
148
149 #[cfg(target_arch = "x86_64")]
150 #[target_feature(enable = "rdrand")]
151 fn rdrand_u64() -> Option<u64> {
152 rdrand()
153 }
154
155 #[cfg(target_arch = "x86")]
156 #[target_feature(enable = "rdrand")]
157 fn rdrand_u32() -> Option<u32> {
158 rdrand()
159 }
160
161 #[cfg(target_arch = "x86")]
162 #[target_feature(enable = "rdrand")]
163 fn rdrand_u64() -> Option<u64> {
164 let a = rdrand()?;
165 let b = rdrand()?;
166 Some((u64::from(a) << 32) | u64::from(b))
167 }
168
169 #[inline]
170 pub fn inner_u32() -> Result<u32, Error> {
171 if !is_rdrand_good() {
172 return Err(Error::NO_RDRAND);
173 }
174 // SAFETY: After this point, we know rdrand is supported.
175 unsafe { rdrand_u32() }.ok_or(Error::FAILED_RDRAND)
176 }
177
178 #[inline]
179 pub fn inner_u64() -> Result<u64, Error> {
180 if !is_rdrand_good() {
181 return Err(Error::NO_RDRAND);
182 }
183 // SAFETY: After this point, we know rdrand is supported.
184 unsafe { rdrand_u64() }.ok_or(Error::FAILED_RDRAND)
185 }
186
187 #[inline]
188 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
189 if !is_rdrand_good() {
190 return Err(Error::NO_RDRAND);
191 }
192 // SAFETY: After this point, we know rdrand is supported.
193 unsafe { rdrand_exact(dest) }.ok_or(Error::FAILED_RDRAND)
194 }
195
196 impl Error {
197 /// RDRAND instruction failed due to a hardware issue.
198 pub(crate) const FAILED_RDRAND: Error = Self::new_internal(10);
199 /// RDRAND instruction unsupported on this target.
200 pub(crate) const NO_RDRAND: Error = Self::new_internal(11);
201 }