Skip to content
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

Only avoid pointer casts when using miri #545

Merged
merged 2 commits into from
Apr 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1104,14 +1104,31 @@ unsafe fn release_shared(ptr: *mut Shared) {
Box::from_raw(ptr);
}

// Ideally we would always use this version of `ptr_map` since it is strict
// provenance compatible, but it results in worse codegen. We will however still
// use it on miri because it gives better diagnostics for people who test bytes
// code with miri.
//
// See https://github.com/tokio-rs/bytes/pull/545 for more info.
#[cfg(miri)]
fn ptr_map<F>(ptr: *mut u8, f: F) -> *mut u8
where
F: FnOnce(usize) -> usize,
{
let old_addr = ptr as usize;
let new_addr = f(old_addr);
// this optimizes better than `ptr.wrapping_add(new_addr.wrapping_sub(old_addr))`
ptr.wrapping_sub(old_addr).wrapping_add(new_addr)
let diff = new_addr.wrapping_sub(old_addr);
ptr.wrapping_add(diff)
}

#[cfg(not(miri))]
fn ptr_map<F>(ptr: *mut u8, f: F) -> *mut u8
where
F: FnOnce(usize) -> usize,
{
let old_addr = ptr as usize;
let new_addr = f(old_addr);
new_addr as *mut u8
Comment on lines +1113 to +1131
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps this is a bit pedantic, but this really feels like it ought to have a comment on it, IMO. To someone who doesn't know the specific reason for this, it seems quite suspect that we only do the "correct" thing under Miri, and the "real" code does the thing that's not strict provenance compliant. A comment saying that the thing that's theoretically "correct" under strict provenance actually results in miscompiles in real life, and references the appropriate rustc issue etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You aren't being pedantic. I added a link to this PR, which has links to the previous PR and the rust issue.

}

// compile-fails
Expand Down