aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / getrandom / src / windows.rs
| 1 | //! Implementation for Windows |
| 2 | use crate::Error; |
| 3 | use core::{ffi::c_void, mem::MaybeUninit, num::NonZeroU32, ptr}; |
| 4 | |
| 5 | const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002; |
| 6 | |
| 7 | #[link(name = "bcrypt")] |
| 8 | extern "system" { |
| 9 | fn BCryptGenRandom( |
| 10 | hAlgorithm: *mut c_void, |
| 11 | pBuffer: *mut u8, |
| 12 | cbBuffer: u32, |
| 13 | dwFlags: u32, |
| 14 | ) -> i32; |
| 15 | } |
| 16 | |
| 17 | // Forbidden when targetting UWP |
| 18 | #[cfg(not(target_vendor = "uwp"))] |
| 19 | #[link(name = "advapi32")] |
| 20 | extern "system" { |
| 21 | #[link_name = "SystemFunction036"] |
| 22 | fn RtlGenRandom(RandomBuffer: *mut c_void, RandomBufferLength: u32) -> u8; |
| 23 | } |
| 24 | |
| 25 | pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 26 | // Prevent overflow of u32 |
| 27 | for chunk in dest.chunks_mut(u32::max_value() as usize) { |
| 28 | // BCryptGenRandom was introduced in Windows Vista |
| 29 | let ret = unsafe { |
| 30 | BCryptGenRandom( |
| 31 | ptr::null_mut(), |
| 32 | chunk.as_mut_ptr() as *mut u8, |
| 33 | chunk.len() as u32, |
| 34 | BCRYPT_USE_SYSTEM_PREFERRED_RNG, |
| 35 | ) |
| 36 | }; |
| 37 | let ret = ret as u32; |
| 38 | // NTSTATUS codes use the two highest bits for severity status. |
| 39 | if ret >> 30 == 0b11 { |
| 40 | // Failed. Try RtlGenRandom as a fallback. |
| 41 | #[cfg(not(target_vendor = "uwp"))] |
| 42 | { |
| 43 | let ret = |
| 44 | unsafe { RtlGenRandom(chunk.as_mut_ptr() as *mut c_void, chunk.len() as u32) }; |
| 45 | if ret != 0 { |
| 46 | continue; |
| 47 | } |
| 48 | } |
| 49 | // We zeroize the highest bit, so the error code will reside |
| 50 | // inside the range designated for OS codes. |
| 51 | let code = ret ^ (1 << 31); |
| 52 | // SAFETY: the second highest bit is always equal to one, |
| 53 | // so it's impossible to get zero. Unfortunately the type |
| 54 | // system does not have a way to express this yet. |
| 55 | let code = unsafe { NonZeroU32::new_unchecked(code) }; |
| 56 | return Err(Error::from(code)); |
| 57 | } |
| 58 | } |
| 59 | Ok(()) |
| 60 | } |