Skip to content

Commit

Permalink
Merge branch 'master' into efi_rng
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov authored Dec 18, 2024
2 parents 9829eba + 9b902af commit a14c317
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 35 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,9 @@ jobs:
toolchain: nightly-2024-10-08
components: rust-src
- env:
RUSTFLAGS: -Dwarnings -Zsanitizer=memory --cfg getrandom_sanitize
# `--all-targets` is used to skip doc tests which currently fail linking
run: cargo test -Zbuild-std --target=x86_64-unknown-linux-gnu --all-targets
RUSTFLAGS: -Dwarnings -Zsanitizer=memory
RUSTDOCFLAGS: -Dwarnings -Zsanitizer=memory
run: cargo test -Zbuild-std --target=x86_64-unknown-linux-gnu

cross:
name: Cross
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Error::new_custom` method [#507]
- `rndr` opt-in backend [#512]
- `linux_rustix` opt-in backend [#520]
- Memory sanitizer support gated behind `getrandom_sanitize` configuration flag [#521]
- Automatic MemorySanitizer support [#521] [#571]
- `u32` and `u64` functions for generating random values of the respective type [#544]
- `efi_rng` opt-in backend [#570]

Expand All @@ -63,6 +63,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#555]: https://github.com/rust-random/getrandom/pull/555
[#557]: https://github.com/rust-random/getrandom/pull/557
[#570]: https://github.com/rust-random/getrandom/pull/570
[#571]: https://github.com/rust-random/getrandom/pull/571

## [0.2.15] - 2024-05-06
### Added
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ rustc-dep-of-std = ["dep:compiler_builtins", "dep:core"]
level = "warn"
check-cfg = [
'cfg(getrandom_backend, values("custom", "rdrand", "rndr", "linux_getrandom", "linux_rustix", "wasm_js", "efi_rng", "esp_idf"))',
'cfg(getrandom_sanitize)',
'cfg(getrandom_msan)',
'cfg(getrandom_test_linux_fallback)',
'cfg(getrandom_test_netbsd_fallback)',
]
Expand Down
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,15 +268,14 @@ our code should correctly handle it and return an error, e.g.

## Sanitizer support

If your code uses [`fill_uninit`] and you enable memory sanitization
(i.e. `-Zsanitizer=memory`), you need to pass the `getrandom_sanitize`
configuration flag to enable unpoisoning of the destination buffer
filled by `fill_uninit`.
If your code uses [`fill_uninit`] and you enable
[MemorySanitizer](https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html#memorysanitizer)
(i.e. `-Zsanitizer=memory`), we will automatically handle unpoisoning
of the destination buffer filled by `fill_uninit`.

For example, it can be done as follows (requires a Nightly compiler):
You can run sanitizer tests for your crate dependent on `getrandom` like this:
```sh
RUSTFLAGS="-Zsanitizer=memory --cfg getrandom_sanitize" \
cargo test -Zbuild-std --target=x86_64-unknown-linux-gnu
RUSTFLAGS="-Zsanitizer=memory" cargo test -Zbuild-std --target=x86_64-unknown-linux-gnu
```

## Minimum Supported Rust Version
Expand Down
9 changes: 9 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Automatically detect cfg(sanitize = "memory") even if cfg(sanitize) isn't
// supported. Build scripts get cfg() info, even if the cfg is unstable.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let santizers = std::env::var("CARGO_CFG_SANITIZE").unwrap_or_default();
if santizers.contains("memory") {
println!("cargo:rustc-cfg=getrandom_msan");
}
}
41 changes: 28 additions & 13 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ extern crate std;

use core::{fmt, num::NonZeroU32};

// This private alias mirrors `std::io::RawOsError`:
// https://doc.rust-lang.org/std/io/type.RawOsError.html)
cfg_if::cfg_if!(
if #[cfg(target_os = "uefi")] {
type RawOsError = usize;
} else {
type RawOsError = i32;
}
);

/// A small and `no_std` compatible error type
///
/// The [`Error::raw_os_error()`] will indicate if the error is from the OS, and
Expand Down Expand Up @@ -57,20 +67,25 @@ impl Error {
/// Extract the raw OS error code (if this error came from the OS)
///
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except
/// that it works in `no_std` contexts. If this method returns `None`, the
/// error value can still be formatted via the `Display` implementation.
/// that it works in `no_std` contexts. On most targets this method returns
/// `Option<i32>`, but some platforms (e.g. UEFI) may use a different primitive
/// type like `usize`. Consult with the [`RawOsError`] docs for more information.
///
/// If this method returns `None`, the error value can still be formatted via
/// the `Display` implementation.
///
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.raw_os_error
/// [`RawOsError`]: https://doc.rust-lang.org/std/io/type.RawOsError.html
#[inline]
pub fn raw_os_error(self) -> Option<i32> {
i32::try_from(self.0.get()).ok().map(|errno| {
// On SOLID, negate the error code again to obtain the original error code.
if cfg!(target_os = "solid_asp3") {
-errno
} else {
errno
}
})
pub fn raw_os_error(self) -> Option<RawOsError> {
let code = self.0.get();
if code >= Self::INTERNAL_START {
return None;
}
let errno = RawOsError::try_from(code).ok()?;
#[cfg(target_os = "solid_asp3")]
let errno = -errno;
Some(errno)
}

/// Creates a new instance of an `Error` from a particular custom error code.
Expand Down Expand Up @@ -134,7 +149,7 @@ impl fmt::Debug for Error {
let mut dbg = f.debug_struct("Error");
if let Some(errno) = self.raw_os_error() {
dbg.field("os_error", &errno);
#[cfg(all(feature = "std", not(target_os = "uefi")))]
#[cfg(feature = "std")]
dbg.field("description", &std::io::Error::from_raw_os_error(errno));
} else if let Some(desc) = self.internal_desc() {
dbg.field("internal_code", &self.0.get());
Expand All @@ -150,7 +165,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(errno) = self.raw_os_error() {
cfg_if! {
if #[cfg(all(feature = "std", not(target_os = "uefi")))] {
if #[cfg(feature = "std")] {
std::io::Error::from_raw_os_error(errno).fmt(f)
} else {
write!(f, "OS Error: {}", errno)
Expand Down
5 changes: 0 additions & 5 deletions src/error_std_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,10 @@ use std::io;

impl From<Error> for io::Error {
fn from(err: Error) -> Self {
#[cfg(not(target_os = "uefi"))]
match err.raw_os_error() {
Some(errno) => io::Error::from_raw_os_error(errno),
None => io::Error::new(io::ErrorKind::Other, err),
}
#[cfg(target_os = "uefi")]
{
io::Error::new(io::ErrorKind::Other, err)
}
}
}

Expand Down
7 changes: 2 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#![doc = include_str!("../README.md")]
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(getrandom_sanitize, feature(cfg_sanitize))]
#![cfg_attr(getrandom_backend = "efi_rng", feature(uefi_std))]
#![deny(
clippy::cast_lossless,
Expand Down Expand Up @@ -100,17 +99,15 @@ pub fn fill_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
backends::fill_inner(dest)?;
}

#[cfg(getrandom_sanitize)]
#[cfg(sanitize = "memory")]
#[cfg(getrandom_msan)]
extern "C" {
fn __msan_unpoison(a: *mut core::ffi::c_void, size: usize);
}

// SAFETY: `dest` has been fully initialized by `imp::fill_inner`
// since it returned `Ok`.
Ok(unsafe {
#[cfg(getrandom_sanitize)]
#[cfg(sanitize = "memory")]
#[cfg(getrandom_msan)]
__msan_unpoison(dest.as_mut_ptr().cast(), dest.len());

util::slice_assume_init_mut(dest)
Expand Down

0 comments on commit a14c317

Please sign in to comment.