Skip to content

Commit

Permalink
Fix miri failures by preserving provenance in BitSpan::new_unchecked
Browse files Browse the repository at this point in the history
Fix the miri failures in doctests, see issue ferrilab#135. The issue is that miri doesn't guess
correct provenance in the int-to-ptr cast in `BitSpan::new_unchecked`, as was found by
@tavianator [here](rust-lang/miri#1866 (comment)).

The solution is to preserve provenance and was proposed by  @tavianator
[here](rust-lang/miri#1866 (comment)).
With this change the entire test suite passes under miri.
  • Loading branch information
niluxv committed Dec 25, 2021
1 parent 9574c04 commit 743e845
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/devel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,9 @@ where
{
TypeId::of::<T>() == TypeId::of::<U>()
}

/// Converts `addr` to a pointer using the provenance of `prov`.
pub fn int_to_ptr_with_provenance<T>(addr: usize, prov: *const T) -> *const T {
let ptr = prov.cast::<u8>();
ptr.wrapping_add(addr.wrapping_sub(ptr as usize)).cast()
}
7 changes: 6 additions & 1 deletion src/ptr/span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ use super::{
MisalignError,
};
use crate::{
devel::int_to_ptr_with_provenance,
index::{
BitEnd,
BitIdx,
Expand Down Expand Up @@ -205,12 +206,16 @@ where
let head = head.into_inner() as usize;
let ptr_data = addr.to_const() as usize & Self::PTR_ADDR_MASK;
let ptr_head = head >> Self::LEN_HEAD_BITS;
// We need to preserve pointer provenance for miri, see miri issue 1866
// <https://github.com/rust-lang/miri/issues/1866#issuecomment-985770125>
let ptr =
int_to_ptr_with_provenance(ptr_data | ptr_head, addr.to_const());

let len_head = head & Self::LEN_HEAD_MASK;
let len_bits = bits << Self::LEN_HEAD_BITS;

Self {
ptr: NonNull::new_unchecked((ptr_data | ptr_head) as *mut ()),
ptr: NonNull::new_unchecked(ptr as *mut ()),
len: len_bits | len_head,
..Self::EMPTY
}
Expand Down

0 comments on commit 743e845

Please sign in to comment.