1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 use crate::Error;
10 use core::{ffi::c_void, num::NonZeroU32, ptr};
11
12 const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002;
13
14 extern "system" {
BCryptGenRandom( hAlgorithm: *mut c_void, pBuffer: *mut u8, cbBuffer: u32, dwFlags: u32, ) -> u3215 fn BCryptGenRandom(
16 hAlgorithm: *mut c_void,
17 pBuffer: *mut u8,
18 cbBuffer: u32,
19 dwFlags: u32,
20 ) -> u32;
21 }
22
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>23 pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
24 // Prevent overflow of u32
25 for chunk in dest.chunks_mut(u32::max_value() as usize) {
26 let ret = unsafe {
27 BCryptGenRandom(
28 ptr::null_mut(),
29 chunk.as_mut_ptr(),
30 chunk.len() as u32,
31 BCRYPT_USE_SYSTEM_PREFERRED_RNG,
32 )
33 };
34 // NTSTATUS codes use the two highest bits for severity status.
35 if ret >> 30 == 0b11 {
36 // We zeroize the highest bit, so the error code will reside
37 // inside the range designated for OS codes.
38 let code = ret ^ (1 << 31);
39 // SAFETY: the second highest bit is always equal to one,
40 // so it's impossible to get zero. Unfortunately the type
41 // system does not have a way to express this yet.
42 let code = unsafe { NonZeroU32::new_unchecked(code) };
43 return Err(Error::from(code));
44 }
45 }
46 Ok(())
47 }
48