Debian Codegraph @

.cargo/vendor/getrandom/src/backends/windows_legacy.rs

raw
1 //! Legacy implementation for Windows XP and later
2 //!
3 //! For targets where we cannot use ProcessPrng (added in Windows 10), we use
4 //! RtlGenRandom. See windows.rs for a more detailed discussion of the Windows
5 //! RNG APIs (and why we don't use BCryptGenRandom). On versions prior to
6 //! Windows 10, this implementation is secure. On Windows 10 and later, this
7 //! implementation behaves identically to the windows.rs implementation, except
8 //! that it forces the loading of an additional DLL (advapi32.dll).
9 //!
10 //! This implementation will not work on UWP targets (which lack advapi32.dll),
11 //! but such targets require Windows 10, so can use the standard implementation.
12 use crate::Error;
13 use core::{ffi::c_void, mem::MaybeUninit};
14
15 pub use crate::util::{inner_u32, inner_u64};
16
17 #[cfg(not(windows))]
18 compile_error!("`windows_legacy` backend can be enabled only for Windows targets!");
19
20 // Binding to the Windows.Win32.Security.Authentication.Identity.RtlGenRandom
21 // API. Don't use windows-targets as it doesn't support Windows 7 targets.
22 #[link(name = "advapi32")]
23 extern "system" {
24 #[link_name = "SystemFunction036"]
25 fn RtlGenRandom(randombuffer: *mut c_void, randombufferlength: u32) -> BOOLEAN;
26 }
27 #[allow(clippy::upper_case_acronyms)]
28 type BOOLEAN = u8;
29 const TRUE: BOOLEAN = 1u8;
30
31 #[inline]
32 pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
33 // Prevent overflow of u32
34 let chunk_size = usize::try_from(i32::MAX).expect("Windows does not support 16-bit targets");
35 for chunk in dest.chunks_mut(chunk_size) {
36 let chunk_len = u32::try_from(chunk.len()).expect("chunk size is bounded by i32::MAX");
37 let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr().cast::<c_void>(), chunk_len) };
38 if ret != TRUE {
39 return Err(Error::WINDOWS_RTL_GEN_RANDOM);
40 }
41 }
42 Ok(())
43 }
44
45 impl Error {
46 /// Call to Windows [`RtlGenRandom`](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom) failed.
47 pub(crate) const WINDOWS_RTL_GEN_RANDOM: Error = Self::new_internal(10);
48 }