Skip to content

Commit 9358531

Browse files
authored
Use getrandom for randomness (#110)
1 parent ebd3841 commit 9358531

File tree

3 files changed

+44
-30
lines changed

3 files changed

+44
-30
lines changed

Cargo.lock

Lines changed: 39 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ libc = "0.2.87"
1818
[target.'cfg(unix)'.dev-dependencies]
1919
nix = { version = "0.28.0", features = ["fs"] }
2020

21+
[target.'cfg(windows)'.dependencies]
22+
getrandom = { version = "0.3.2", features = ["std"] }
23+
2124
[dev-dependencies]
2225
tempfile = "3.10.1"
2326

src/windows.rs

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -67,31 +67,6 @@ extern "system" {
6767
fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
6868
}
6969

70-
#[link(name = "advapi32")]
71-
extern "system" {
72-
#[link_name = "SystemFunction036"]
73-
fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: u32) -> u8;
74-
}
75-
76-
// Note that we ideally would use the `getrandom` crate, but unfortunately
77-
// that causes build issues when this crate is used in rust-lang/rust (see
78-
// rust-lang/rust#65014 for more information). As a result we just inline
79-
// the pretty simple Windows-specific implementation of generating
80-
// randomness.
81-
fn getrandom(dest: &mut [u8]) -> io::Result<()> {
82-
// Prevent overflow of u32
83-
for chunk in dest.chunks_mut(u32::MAX as usize) {
84-
let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr(), chunk.len() as u32) };
85-
if ret == 0 {
86-
return Err(io::Error::new(
87-
io::ErrorKind::Other,
88-
"failed to generate random bytes",
89-
));
90-
}
91-
}
92-
Ok(())
93-
}
94-
9570
impl Client {
9671
pub fn new(limit: usize) -> io::Result<Client> {
9772
// Try a bunch of random semaphore names until we get a unique one,
@@ -103,9 +78,8 @@ impl Client {
10378
// slot and then immediately acquire it (without ever releaseing it
10479
// back).
10580
for _ in 0..100 {
106-
let mut bytes = [0; 4];
107-
getrandom(&mut bytes)?;
108-
let mut name = format!("__rust_jobserver_semaphore_{}\0", u32::from_ne_bytes(bytes));
81+
let bytes = getrandom::u32()?;
82+
let mut name = format!("__rust_jobserver_semaphore_{}\0", bytes);
10983
unsafe {
11084
let create_limit = if limit == 0 { 1 } else { limit };
11185
let r = CreateSemaphoreA(

0 commit comments

Comments
 (0)