std: rand: Use BCrypt on UWP

As Rtl* functions are not allowed there
This commit is contained in:
Hugo Beauzée-Luyssen 2019-05-27 16:41:52 +02:00
parent 642f8cd9c2
commit 9407ed759f
3 changed files with 43 additions and 2 deletions

View file

@ -41,6 +41,8 @@ fn main() {
println!("cargo:rustc-link-lib=resolv");
} else if target.contains("uwp") {
println!("cargo:rustc-link-lib=ws2_32");
// For BCryptGenRandom
println!("cargo:rustc-link-lib=bcrypt");
} else if target.contains("windows") {
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=ws2_32");

View file

@ -655,6 +655,29 @@ pub struct timeval {
pub tv_usec: c_long,
}
// Functions forbidden when targeting UWP
cfg_if::cfg_if! {
if #[cfg(not(target_vendor = "uwp"))] {
extern "system" {
#[link_name = "SystemFunction036"]
pub fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: ULONG) -> BOOLEAN;
}
}
}
// UWP specific functions & types
cfg_if::cfg_if! {
if #[cfg(target_vendor = "uwp")] {
pub const BCRYPT_USE_SYSTEM_PREFERRED_RNG: DWORD = 0x00000002;
extern "system" {
pub fn BCryptGenRandom(hAlgorithm: LPVOID, pBuffer: *mut u8,
cbBuffer: ULONG, dwFlags: ULONG) -> LONG;
}
}
}
// Shared between Desktop & UWP
extern "system" {
pub fn WSAStartup(wVersionRequested: WORD,
lpWSAData: LPWSADATA) -> c_int;
@ -950,8 +973,6 @@ extern "system" {
exceptfds: *mut fd_set,
timeout: *const timeval) -> c_int;
#[link_name = "SystemFunction036"]
pub fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: ULONG) -> BOOLEAN;
pub fn GetProcessHeap() -> HANDLE;
pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID;

View file

@ -2,6 +2,7 @@ use crate::io;
use crate::mem;
use crate::sys::c;
#[cfg(not(target_vendor = "uwp"))]
pub fn hashmap_random_keys() -> (u64, u64) {
let mut v = (0, 0);
let ret = unsafe {
@ -14,3 +15,20 @@ pub fn hashmap_random_keys() -> (u64, u64) {
}
return v
}
#[cfg(target_vendor = "uwp")]
pub fn hashmap_random_keys() -> (u64, u64) {
use crate::ptr;
let mut v = (0, 0);
let ret = unsafe {
c::BCryptGenRandom(ptr::null_mut(), &mut v as *mut _ as *mut u8,
mem::size_of_val(&v) as c::ULONG,
c::BCRYPT_USE_SYSTEM_PREFERRED_RNG)
};
if ret != 0 {
panic!("couldn't generate random bytes: {}",
io::Error::last_os_error());
}
return v
}