Skip to content

Commit d4710c0

Browse files
committed
std: sys: random: uefi: Provide rdrand based fallback
Some UEFI systems based on American Megatrends Inc. v3.3 do not provide RNG support [1]. So fallback to rdrand in such cases. [1]: #138252 (comment) Signed-off-by: Ayush Singh <[email protected]>
1 parent 6cab15c commit d4710c0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

library/std/src/sys/random/uefi.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,39 @@ pub fn fill_bytes(bytes: &mut [u8]) {
2323
}
2424
}
2525

26+
// Fallback to rdrand if rng protocol missing.
27+
//
28+
// For real-world example, see [issue-13825](https://github.com/rust-lang/rust/issues/138252#issuecomment-2891270323)
29+
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
30+
if crate::is_x86_feature_detected!("rdrand") {
31+
#[cfg(target_arch = "x86_64")]
32+
for chunk in bytes.chunks_mut(core::mem::size_of::<u64>()) {
33+
let mut rand_val: u64 = 0;
34+
unsafe {
35+
if core::arch::x86_64::_rdrand64_step(&mut rand_val) == 0 {
36+
panic!("failed to generate random data using rdrand");
37+
}
38+
}
39+
40+
let bytes = rand_val.to_le_bytes();
41+
chunk.copy_from_slice(&bytes[..chunk.len()]);
42+
}
43+
44+
#[cfg(target_arch = "x86")]
45+
for chunk in bytes.chunks_mut(core::mem::size_of::<u32>()) {
46+
let mut rand_val: u32 = 0;
47+
unsafe {
48+
if core::arch::x86::_rdrand32_step(&mut rand_val) == 0 {
49+
panic!("failed to generate random data using rdrand");
50+
}
51+
}
52+
53+
let bytes = rand_val.to_le_bytes();
54+
chunk.copy_from_slice(&bytes[..chunk.len()]);
55+
}
56+
57+
return;
58+
}
59+
2660
panic!("failed to generate random data");
2761
}

0 commit comments

Comments
 (0)