Skip to content

Use getrandom for randomness #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ libc = "0.2.87"
[target.'cfg(unix)'.dev-dependencies]
nix = { version = "0.28.0", features = ["fs"] }

[target.'cfg(windows)'.dependencies]
getrandom = { version = "0.3.2", features = ["std"] }

[dev-dependencies]
tempfile = "3.10.1"

Expand Down
30 changes: 2 additions & 28 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,31 +67,6 @@ extern "system" {
fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
}

#[link(name = "advapi32")]
extern "system" {
#[link_name = "SystemFunction036"]
fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: u32) -> u8;
}

// Note that we ideally would use the `getrandom` crate, but unfortunately
// that causes build issues when this crate is used in rust-lang/rust (see
// rust-lang/rust#65014 for more information). As a result we just inline
// the pretty simple Windows-specific implementation of generating
// randomness.
fn getrandom(dest: &mut [u8]) -> io::Result<()> {
// Prevent overflow of u32
for chunk in dest.chunks_mut(u32::MAX as usize) {
let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr(), chunk.len() as u32) };
if ret == 0 {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to generate random bytes",
));
}
}
Ok(())
}

impl Client {
pub fn new(limit: usize) -> io::Result<Client> {
// Try a bunch of random semaphore names until we get a unique one,
Expand All @@ -103,9 +78,8 @@ impl Client {
// slot and then immediately acquire it (without ever releaseing it
// back).
for _ in 0..100 {
let mut bytes = [0; 4];
getrandom(&mut bytes)?;
let mut name = format!("__rust_jobserver_semaphore_{}\0", u32::from_ne_bytes(bytes));
let bytes = getrandom::u32()?;
let mut name = format!("__rust_jobserver_semaphore_{}\0", bytes);
unsafe {
let create_limit = if limit == 0 { 1 } else { limit };
let r = CreateSemaphoreA(
Expand Down
Loading