Skip to content

Commit

Permalink
linux_android_with_fallback: avoid dlsym on musl
Browse files Browse the repository at this point in the history
The dlsym-based getrandom detection added in commit 869a4f0
("linux_android: use libc::getrandom") assumes dynamic linking, which
means it never works properly on musl where static linking is the norm.
Add some conditional compilation to use `libc::getrandom` directly on
musl while retaining kernel support detection.
  • Loading branch information
tamird committed Feb 3, 2025
1 parent ce3b017 commit 0b1df36
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 56 deletions.
101 changes: 48 additions & 53 deletions src/backends/linux_android_with_fallback.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,55 @@
//! Implementation for Linux / Android with `/dev/urandom` fallback
use super::use_file;
use crate::Error;
use core::{
ffi::c_void,
mem::{self, MaybeUninit},
ptr::{self, NonNull},
sync::atomic::{AtomicPtr, Ordering},
};
use core::{ffi::c_void, mem::MaybeUninit, ptr};
use use_file::util_libc;

#[path = "../lazy.rs"]
mod lazy;

pub use crate::util::{inner_u32, inner_u64};

type GetRandomFn = unsafe extern "C" fn(*mut c_void, libc::size_t, libc::c_uint) -> libc::ssize_t;

/// Sentinel value which indicates that `libc::getrandom` either not available,
/// or not supported by kernel.
const NOT_AVAILABLE: NonNull<c_void> = unsafe { NonNull::new_unchecked(usize::MAX as *mut c_void) };
#[cfg(target_os = "android")]
#[cold]
#[inline(never)]
fn get_getrandom_fn() -> Option<GetRandomFn> {
static GETRANDOM_FN: lazy::LazyUsize = lazy::LazyUsize::new();

static GETRANDOM_FN: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
let raw_ptr = GETRANDOM_FN.unsync_init(|| {
static NAME: &[u8] = b"getrandom\0";
let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) as usize }
}) as *mut c_void;

(!raw_ptr.is_null()).then(|| {
// note: `transmute` is currently the only way to convert a pointer into a function reference
unsafe { core::mem::transmute::<*mut c_void, GetRandomFn>(raw_ptr) }
})
}

#[cold]
#[inline(never)]
fn init() -> NonNull<c_void> {
static NAME: &[u8] = b"getrandom\0";
let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
let raw_ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) };
let res_ptr = match NonNull::new(raw_ptr) {
Some(fptr) => {
let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
let dangling_ptr = ptr::NonNull::dangling().as_ptr();
// Check that `getrandom` syscall is supported by kernel
let res = unsafe { getrandom_fn(dangling_ptr, 0, 0) };
if cfg!(getrandom_test_linux_fallback) {
NOT_AVAILABLE
} else if res.is_negative() {
match util_libc::last_os_error().raw_os_error() {
Some(libc::ENOSYS) => NOT_AVAILABLE, // No kernel support
// The fallback on EPERM is intentionally not done on Android since this workaround
// seems to be needed only for specific Linux-based products that aren't based
// on Android. See https://github.com/rust-random/getrandom/issues/229.
#[cfg(target_os = "linux")]
Some(libc::EPERM) => NOT_AVAILABLE, // Blocked by seccomp
_ => fptr,
}
} else {
fptr
}
fn check_getrandom(getrandom_fn: GetRandomFn) -> bool {
let dangling_ptr = ptr::NonNull::dangling().as_ptr();
// Check that `getrandom` syscall is supported by kernel
let res = unsafe { getrandom_fn(dangling_ptr, 0, 0) };
if cfg!(getrandom_test_linux_fallback) {
false
} else if res.is_negative() {
match util_libc::last_os_error().raw_os_error() {
Some(libc::ENOSYS) => false, // No kernel support
// The fallback on EPERM is intentionally not done on Android since this workaround
// seems to be needed only for specific Linux-based products that aren't based
// on Android. See https://github.com/rust-random/getrandom/issues/229.
#[cfg(target_os = "linux")]
Some(libc::EPERM) => false, // Blocked by seccomp
_ => true,
}
None => NOT_AVAILABLE,
};

GETRANDOM_FN.store(res_ptr.as_ptr(), Ordering::Release);
res_ptr
} else {
true
}
}

// prevent inlining of the fallback implementation
Expand All @@ -62,23 +60,20 @@ fn use_file_fallback(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {

#[inline]
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Despite being only a single atomic variable, we still cannot always use
// Ordering::Relaxed, as we need to make sure a successful call to `init`
// is "ordered before" any data read through the returned pointer (which
// occurs when the function is called). Our implementation mirrors that of
// the one in libstd, meaning that the use of non-Relaxed operations is
// probably unnecessary.
let raw_ptr = GETRANDOM_FN.load(Ordering::Acquire);
let fptr = match NonNull::new(raw_ptr) {
Some(p) => p,
None => init(),
static GETRANDOM_GOOD: lazy::LazyBool = lazy::LazyBool::new();

#[cfg(not(target_os = "android"))]
let getrandom_fn = libc::getrandom;

#[cfg(target_os = "android")]
let getrandom_fn = match get_getrandom_fn() {
Some(f) => f,
None => return use_file_fallback(dest),
};

if fptr == NOT_AVAILABLE {
if !GETRANDOM_GOOD.unsync_init(|| check_getrandom(getrandom_fn)) {
use_file_fallback(dest)
} else {
// note: `transmute` is currently the only way to convert a pointer into a function reference
let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
util_libc::sys_fill_exact(dest, |buf| unsafe {
getrandom_fn(buf.as_mut_ptr().cast(), buf.len(), 0)
})
Expand Down
6 changes: 3 additions & 3 deletions src/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@ use core::sync::atomic::{AtomicUsize, Ordering};
// }
// the effects of c() or writes to shared memory will not necessarily be
// observed and additional synchronization methods may be needed.
struct LazyUsize(AtomicUsize);
pub(crate) struct LazyUsize(AtomicUsize);

impl LazyUsize {
// The initialization is not completed.
const UNINIT: usize = usize::MAX;

const fn new() -> Self {
pub const fn new() -> Self {
Self(AtomicUsize::new(Self::UNINIT))
}

// Runs the init() function at most once, returning the value of some run of
// init(). Multiple callers can run their init() functions in parallel.
// init() should always return the same value, if it succeeds.
fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize {
pub fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize {
#[cold]
fn do_init(this: &LazyUsize, init: impl FnOnce() -> usize) -> usize {
let val = init();
Expand Down

0 comments on commit 0b1df36

Please sign in to comment.