Skip to content

Commit

Permalink
fix: fix unaligned pointer access in getrandom (#206)
Browse files Browse the repository at this point in the history
* fix unaligned pointer access

Signed-off-by: Runji Wang <[email protected]>

* revert version bump as this is not urgent

Signed-off-by: Runji Wang <[email protected]>

---------

Signed-off-by: Runji Wang <[email protected]>
  • Loading branch information
wangrunji0408 authored Apr 23, 2024
1 parent 91a8231 commit cccdc33
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Fix unaligned pointer access in getrandom.

## tokio [0.2.25] - 2024-04-08

### Removed
Expand Down
18 changes: 6 additions & 12 deletions madsim/src/sim/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,26 +194,20 @@ thread_local! {
/// Ref: <https://man7.org/linux/man-pages/man2/getrandom.2.html>
#[no_mangle]
#[inline(never)]
unsafe extern "C" fn getrandom(mut buf: *mut u8, mut buflen: usize, _flags: u32) -> isize {
unsafe extern "C" fn getrandom(buf: *mut u8, buflen: usize, _flags: u32) -> isize {
if let Some(seed) = SEED.with(|s| s.get()) {
assert_eq!(buflen, 16);
std::slice::from_raw_parts_mut(buf as *mut u64, 2).fill(seed);
SEED.with(|s| s.set(None));
return 16;
} else if let Some(rand) = crate::context::try_current(|h| h.rand.clone()) {
// inside a madsim context, use the global RNG.
let len = buflen;
while buflen >= std::mem::size_of::<u64>() {
(buf as *mut u64).write(rand.with(|rng| rng.gen()));
buf = buf.add(std::mem::size_of::<u64>());
buflen -= std::mem::size_of::<u64>();
if buflen == 0 {
return 0;
}
// note: do not modify state if buflen == 0
if buflen != 0 {
let val = rand.with(|rng| rng.gen::<u64>().to_ne_bytes());
core::ptr::copy(val.as_ptr(), buf, buflen);
}
return len as _;
let buf = std::slice::from_raw_parts_mut(buf, buflen);
rand.with(|rng| rng.fill_bytes(buf));
return buflen as _;
}
#[cfg(target_os = "linux")]
{
Expand Down

0 comments on commit cccdc33

Please sign in to comment.