|
1 | 1 | #![allow(clippy::useless_conversion)] |
2 | 2 | use std::ffi::CString; |
3 | | - |
| 3 | +#[cfg(target_os = "windows")] |
| 4 | +extern crate winapi; |
4 | 5 | use internal_macro::is_runtime; |
5 | 6 |
|
6 | 7 | struct LibC {} |
@@ -87,4 +88,73 @@ impl LibC { |
87 | 88 | ) -> *mut libc::c_void { |
88 | 89 | unsafe { libc::memcpy(dest, src, n) } |
89 | 90 | } |
| 91 | + |
| 92 | + fn getrandom( |
| 93 | + buf: *mut libc::c_void, |
| 94 | + buflen: libc::size_t, |
| 95 | + flags: libc::c_uint, |
| 96 | + ) -> libc::ssize_t { |
| 97 | + getrandom_inner(buf, buflen, flags) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +#[cfg(target_os = "linux")] |
| 102 | +fn getrandom_inner( |
| 103 | + buf: *mut libc::c_void, |
| 104 | + buflen: libc::size_t, |
| 105 | + flags: libc::c_uint, |
| 106 | +) -> libc::ssize_t { |
| 107 | + unsafe { libc::syscall(libc::SYS_getrandom, buf, buflen, flags) as libc::ssize_t } |
| 108 | +} |
| 109 | + |
| 110 | +#[cfg(target_os = "macos")] |
| 111 | +extern "C" { |
| 112 | + // Supported as of macOS 10.12+. |
| 113 | + fn getentropy(buf: *mut u8, size: libc::size_t) -> libc::c_int; |
| 114 | +} |
| 115 | +#[cfg(target_os = "macos")] |
| 116 | +fn getrandom_inner( |
| 117 | + buf: *mut libc::c_void, |
| 118 | + buflen: libc::size_t, |
| 119 | + _flags: libc::c_uint, |
| 120 | +) -> libc::ssize_t { |
| 121 | + unsafe { |
| 122 | + if getentropy(buf as *mut u8, buflen) == 0 { |
| 123 | + return buflen as libc::ssize_t; |
| 124 | + } else { |
| 125 | + return -1; |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +#[cfg(target_os = "windows")] |
| 131 | +fn getrandom_inner( |
| 132 | + buf: *mut libc::c_void, |
| 133 | + buflen: libc::size_t, |
| 134 | + _flags: libc::c_uint, |
| 135 | +) -> libc::ssize_t { |
| 136 | + use core::ptr::null_mut; |
| 137 | + use winapi::um::wincrypt::{ |
| 138 | + CryptAcquireContextA, CryptGenRandom, CryptReleaseContext, CRYPT_VERIFYCONTEXT, HCRYPTPROV, |
| 139 | + PROV_RSA_FULL, |
| 140 | + }; |
| 141 | + let mut hcryptprov: HCRYPTPROV = 0; |
| 142 | + unsafe { |
| 143 | + if CryptAcquireContextA( |
| 144 | + &mut hcryptprov, |
| 145 | + null_mut(), |
| 146 | + null_mut(), |
| 147 | + PROV_RSA_FULL, |
| 148 | + CRYPT_VERIFYCONTEXT, |
| 149 | + ) == 0 |
| 150 | + { |
| 151 | + return -1; |
| 152 | + } |
| 153 | + if CryptGenRandom(hcryptprov, buflen as u32, buf as *mut u8) == 0 { |
| 154 | + CryptReleaseContext(hcryptprov, 0); |
| 155 | + return -1; |
| 156 | + } |
| 157 | + CryptReleaseContext(hcryptprov, 0); |
| 158 | + } |
| 159 | + 0 |
90 | 160 | } |
0 commit comments